簡體   English   中英

C:將.txt文件中的行存儲到二維數組中

[英]C: Storing line from .txt file into a 2d array

我有讀取功能,但最后一行重復了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

我似乎無法弄清楚為什么要重復最后一行。 謝謝!

你應該更換

programs[i] = line;

programs[i] = strdup(line);

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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM