【问题标题】:C: Storing line from .txt file into a 2d arrayC:将 .txt 文件中的行存储到二维数组中
【发布时间】:2015-04-07 00:48:10
【问题描述】:

我有一个读取功能,但最后一行重复了 3 次

 void read()
 {
    FILE *file;
    char line[50];
    int numProgs = 0;
    char* programs[50];
    int i = 0;
    file = fopen("testing.txt", "r");
    while(fgets(line, 50, file) != NULL) {
       printf("%s", line);
       programs[i]=line; 
       i++;
       numProgs++;
     }

    int j = 0;
    for (j=0 ; j<numProgs; j++) {
      printf("\n%s", programs[j]);
    }

     fclose(file);
}

我的 testing.txt 文档包含 3 行(但可以更多)

Jane Smith   123 blue jay st    123-123-3312
John Doe    12 blue st    321-222-1131
Amy White    431 yellow st    +1-23-738-2912

但是,当我运行我的读取功能时,它会显示这个

Jane Smith   123 blue jay st    123-123-3312
John Doe    12 blue st    321-222-1131
Amy White    431 yellow st    +1-23-738-2912
Amy White    431 yellow st    +1-23-738-2912
Amy White    431 yellow st    +1-23-738-2912

我似乎无法弄清楚为什么它会重复最后一行。谢谢!

【问题讨论】:

  • 因为不复制行内容,所以每次读取都会覆盖它。
  • 有什么理由你需要'numProgs'和'i'吗?它们似乎被初始化为相同的值 (0),并且都同时递增。我知道这并不能解决您的问题,但您应该降低代码的复杂性,这样会更容易找到错误。

标签: c string file-io


【解决方案1】:

你应该替换

programs[i] = line;

programs[i] = strdup(line);

【讨论】:

  • 警告*:警告:内置函数“strdup”的隐式声明不兼容
【解决方案2】:

strdup 为例:

FILE *file;
char line[50];
int numProgs = 0;
char* programs[50];
file = fopen("testing.txt", "r");
while(fgets(line, 50, file) && numProgs < 50) {
    printf("%s", line);
    programs[numProgs++;] = strdup(line);
}

for (int j  =0 ; j < numProgs; j++) {
    printf("\n%s", programs[j]);
    free(programs[j]);
}

fclose(file);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多