2016-05-10 83 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; 
    } 
相关问题