我正在嘗試讀取每行中包含名稱和年齡的 .txt 檔案并將它們存盤在一個陣列中,但顯然只有最后一行名稱存盤在陣列的所有位置
我的 .txt 檔案內容:
Pedro 14
Erica 17
Paulo 23
Carlos 27
Mendes 30
Augusto 31
Geraldo 32
我的代碼:
#include <stdio.h>
#include <string.h>
int main() {
FILE *f = fopen("nomes.txt" , "r");
char name[20];
char* listnames[10];
int cont;
while(fscanf(f, "%s %d", name) != EOF) {
listnames[cont] = name;
cont ;
}
fclose(f);
for (int i=0; i<cont; i ) {
printf("%s ", listnames[i]);
}
}
輸出:
Geraldo Geraldo Geraldo Geraldo Geraldo Geraldo Geraldo
uj5u.com熱心網友回復:
您的代碼中有幾個問題:
第一的:
FILE *f = fopen("nomes.txt" , "r");
如果打開檔案失敗怎么辦?
第二:
cont未初始化。您可能希望將其初始化為 0。
第三:
fscanf(f, "%s %d", name)
您正在掃描 achar*和 an int,但您只傳遞了一個引數(即name)。
第四:
char* listnames[10];
...
listnames[cont] = name;
在這里,listnames[cont]沒有初始化。您正在name為每個listnames條目分配地址。您可能希望使用strdup()為字串分配空間,或為此使用靜態陣列。
您的代碼應如下所示:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
FILE *f = fopen("nomes.txt" , "r");
if (!f) { // Handle failure
perror("Could not open file");
return 1;
}
char name[20];
int number;
char* listnames[10]; // (*) char listnames[10][20];
int numbers[10];
int count = 0;
while(fscanf(f, "%s %d", name, &number) != EOF && count < 10) {
listnames[count] = strdup(name); // (*) strcpy(listnames[count], name);
numbers[count] = number; // If you want to save the numbers
count ;
}
fclose(f);
for (int i = 0; i < count; i ) {
printf("%s %d\n", listnames[i], numbers[i]);
free(listnames[i]); // Free space allocated by strdup()
}
}
uj5u.com熱心網友回復:
您忘記在進入 while 回圈之前將 cont 初始化為零。
uj5u.com熱心網友回復:
雖然@user2134584 的評論是正確的,但主要問題是您只分配一個緩沖區,然后讓每個指標參考同一個緩沖區。
char分配指標陣列不會為它們指向的字串分配空間。
相反,您需要做的是這樣的:
#include <stdio.h>
#include <string.h>
int main() {
FILE *f = fopen("nomes.txt" , "r");
char listnames[10][20];
int discard = 0;
int cont = 0;
while(fscanf(f, " s %d", listnames[cont], &discard) != EOF) {
cont ;
}
fclose(f);
for (int i=0; i<cont; i ) {
printf("%s ", listnames[i]);
}
}
請注意,我沒有測驗過這段代碼,但它至少應該讓你走上正軌。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/446350.html
上一篇:影像未顯示在php上
下一篇:創建后檔案不存在
