2016-05-10 81 views
-1

我正在使用C並試圖從文件中讀取文本並將其存儲在數組中以供將來使用,但它似乎不起作用。它也不會給出錯誤。哪裏不對?C從文件中讀取文本並將其放入數組中

#include <stdio.h> 
#include <stdlib.h> 

int main(void) 
{ 
    FILE *fp; 
    fp = fopen("data.txt", "r"); 
    char rida[120], str[100]; 
    int i = 0, j = 0; 

    while (fscanf(fp, "%s", str[i]) != EOF) 
    { 
     rida[i] = str[i]; 
    } 
    fclose(fp); 
} 

的data.txt文件包含以下內容:

Text 
Text2 
Text3 
Text4 
Text5 
+1

'str [i]',真的嗎?你的編譯器告訴你什麼? –

+0

你將個別字符和字符串(字符數組)混合起來。 – lurker

+0

那我該怎麼辦? – Miner123

回答

1

變化rida[120]喜歡的東西rida[20][120],因爲它似乎要每個字存儲在其自己的,所以你需要二維array.Also使用strcpy()複製的字符串,而不是賦值運算符=

#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 

int main(void) 
{ 
    FILE *fp; 
    fp = fopen("data.txt", "r"); 
    char rida[20][120], str[100]; 
    int i = 0, j = 0; 

    while (fscanf(fp, "%s", str) != EOF) 
    { 
     strcpy(rida[i], str); 
     i++; 
    } 
    size_t n; 
    for (n = 0; n < 5; n++) { 
     printf("%s\n", rida[n]); 
    } 
    fclose(fp); 
} 
+0

也許您輸入的最後一個循環用於測試目的,我猜。反正正確答案+1 :) – Cherubim

0

在這裏,你可以選擇使用COMM答案和行參數:

int main(int argc,char *argv[]) 
    { 
     FILE *fp; 
     if(argc<2) return printf("Error.Not enough arguments.\n"),1; 
     if((fp = fopen(argv[1],"r"))==NULL) return printf("Error. Couldn't open the file.\n"),1; 
     char str[10][100]={""}; //Making sure to have only the scaned strings in the array 
     int i=0; 
     while (fscanf(fp,"%s",str[i++]) != EOF); 

     int j=0; 
     while(j<i){ 
     printf("%s\n",str[j++]); 
     } 

     fclose(fp); 
     return 0; 
    } 
相關問題