[英]C program reads the end of file
請查看本文末尾的編輯內容 我有一個 test.dat,其中有 2 行。 第一行是浮點數 (5.0) 第二行是兩個整數,中間用“*”隔開,比如 4*3 浮點數顯示正確(輸出:5.0000)但第二行沒有顯示。 我的老師告訴我在 while 循環之后我犯了一個錯誤。 Fscanf 讀取文件的結尾,而不是開頭。這就是為什么我得到隨機數作為輸出的原因,例如“65746* -8634364”我不知道如何解決它。您的幫助會很好。 這是我的 C 代碼:
#include <stdio.h>
#include <stdlib.h>
int main()
{
float z1;
int z2,z3;
char line[255];
FILE *file;
file = fopen("test.dat", "r");
if (file==NULL)
{
printf("Error\n");
return 1;
}
fscanf(file, "%f", &z1);
printf("%f\n", z1);
while (fscanf(file, "%s", line) == 1)
{
fscanf(file, "%d*%d", &z2, &z3);
printf("%d * %d\n", z2,z3);
}
fclose(file);
return 0;
}
編輯:按照第一個答案的說明進行操作后,我收到了一個新警告警告代碼: In function 'main': main.c:21:2: warning: format '%s' expects argument of type 'char *', but argument 3 has type 'char (*)[255]' [-Wformat=] while (fscanf(file, "%s", &line) ==1) ^
編輯2:由於第一個答案,警告消失了! 還有一個問題:第二行的內容是 "4*3" ,我的輸出是 "0*0" 為什么?
while (fscanf(file, "%s", &line) != EOF)
^ wrong argument is passed to %s
您將一個字符串讀入line
,但line
被聲明為char
變量 -
char line; // will invoke UB if no space is left for '\0'
因此,您需要將line
聲明為char
數組。 像這樣的事情——
char line[255]; //make sure to leave a space for null character
注意 -可能不要針對EOF
測試fscanf
,按如下方式編寫循環條件 -
while (fscanf(file, "%s", line)==1) //will return 1 only if it is successful
/* ^ note- don't pass here &line, just pass line */
你用 fscanf 填充一個 char 變量。 您應該使用 char*,因為您在格式字符串中使用了 %s。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.