[英]Reading and parsing text from a text file in C
題:
我試圖從文件(下面的.txt文件)中讀取每一行,同時將其內容存儲在適當的變量中。 編譯時出現問題。 有人告訴我存在細分錯誤,但不確定為什么會這樣。
tester1.txt文件(不考慮空格)
1/12/04瓊斯,約翰31.11美元
03/12/22迪金森,托尼$ 5.04
2003年12月15日,李(Jerry)$ 21.12
2003年12月19日卡恩,克里斯83.15美元
04/1/31賬單,邁克$ 32.00
1/15/04傑克湖$ 6.66
碼:
int main() {
int month, day, year;
float money;
char *lastname, *firstname;
static const char filename[] = "tester1.txt";
FILE *file = fopen (filename, "r");
if (file != NULL) {
char line [128]; /* or other suitable maximum line size */
while (fgets(line, sizeof line, file ) != NULL) {
sscanf(line,"%d/%d/%d %s, %s $%f", &month, &day, &year, lastname,
firstname, &money);
printf("%d/%d/%d %s, %s $%.2f\n", month, day, year, lastname,
firstname, money );
// printf("valid: %s\n", line);
// fputs ( line, stdout ); /* write the line */
}
fclose (file);
}
else {
perror (filename); /* why didn't the file open? */
}
return 0;
}
您需要為字符串分配內存,不能僅僅將它們聲明為指針:
char lastname[256], firstname[256];
另外,在scanf
您可以指定除逗號(和空格)以外的任何內容,否則逗號也將作為字符串的一部分讀取:
sscanf(line,"%d/%d/%d %[^, ], %s $%f", &month, &day, &year,
lastname, firstname, &money);
首先,您需要為字符串分配內存,就像perreal所說的那樣。 然后,您必須更改sscanf
char str_money[100];
sscanf(line,"%d/%d/%d %s%s%s",
&month, &day, &year, lastname, firstname, str_money);
因為如果您掃描%f,則不會獲得該整潔的浮點數。 而scanf%s只停在太空
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.