gpt4 book ai didi

c - fscanf 读取最后一个整数两次

转载 作者:太空狗 更新时间:2023-10-29 17:00:55 31 4
gpt4 key购买 nike

我有以下简单的程序可以从文本文件 (num.txt) 中读取数据。文本文件的每一行都有数字 1 2 3 4 5。当我运行该程序时,它会打印 5 两次。谁能告诉我为什么会这样,以及如何解决?提前致谢

int main(void)
{
int number;
FILE *file;

int i = 0;;

file = fopen("num.txt", "r");

while (!feof(file)){

fscanf(file, "%d", &number);
printf("%d\n", number);
}

return 0;
}

这是我的文本文件 num.xtx

1
2
3
4
5

这是程序输出

1
2
3
4
5
5

还有5个

最佳答案

来自 scanf 函数族的手册页,

The value EOF is returned if the end of input is reached before either the first successful conversion or a matching failure occurs. EOF is also returned if a read error occurs, in which case the error indicator for the stream is set, and errno is set to indicate the error.

这意味着最后一次成功的 fscanf 调用从流 file 中读取最后一行,之后是 while 循环条件 ! feof(file) 为真,因为尚未满足文件结束条件。这意味着循环会额外执行一次,并且会再次打印变量 number 的先前值。

请阅读此 - while(!feof(file)) is always wrong

您应该检查 scanf 的返回值,而不是检查文件流上的文件结束指示器。

#include <stdio.h>   

int main(void) {
int number;
FILE *file = fopen("num.txt", "r");

// check file for NULL in case there
// is error in opening the file
if(file == NULL) {
printf("error in opening file\n");
return 1;
}

// check if fscanf call is successful
// by checking its return value for 1.
// fscanf returns the number of input
// items successfully matched and assigned
while(fscanf(file, "%d", &number) == 1)
printf("%d\n", number);

return 0;
}

关于c - fscanf 读取最后一个整数两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23185622/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com