我有一個讀出功能,但在最後一行重複3次以上C:存儲從.txt文件線成一個二維數組
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 DOC填充有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
我似乎無法弄清楚它爲什麼重複第l ast線。謝謝!
因爲你沒有複製行內容,每讀覆蓋它。 –
是否有任何理由需要'numProgs'和'我'?它們似乎被初始化爲相同的值(0),並且兩者同時增加。我知道這並不能解決您的問題,但是您應該降低代碼的複雜性,並且這會使錯誤更容易找到。 – Jestin