fscanf读取最后一个整数两次 [英] fscanf reads the last integer twice
问题描述
我有以下简单程序可从文本文件(num.txt)中读取.文本文件每行中的编号为1 2 3 4 5.当我运行该程序时,它将打印两次.谁能告诉我为什么会这样,以及如何解决?预先感谢
I have the following simple program to read from a text file (num.txt). The text file has numbers 1 2 3 4 5 in each line. When I run the program, it prints 5 twice. Can anybody tell me why is this happening, and how to fix it? thanks in advance
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
Here's my text file num.xtx
1
2
3
4
5
这是程序输出
1
2
3
4
5
5
有5个额外的
推荐答案
在scanf
函数族的手册页中,
如果在输入结束之前到达输入结尾,则返回值
EOF
首次成功转换或匹配失败. 如果发生读取错误,也会返回EOF
,在这种情况下,该错误 设置了流的指示符,并且设置了errno
来指示流 错误.
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, anderrno
is set to indicate the error.
这意味着最后一次成功的fscanf
调用从流file
中读取最后一行,在此之后while
循环条件!feof(file)
为真,因为尚未满足文件结尾条件.这意味着循环将再执行一次,并且变量number
的先前值将再次打印.
This means that the last successful fscanf
call reads the last line from the stream file
after which the while
loop condition !feof(file)
is true because the end of file condition is not met yet. This means the loop is executed one extra time and the previous value of the variable number
is printed again.
请仔细阅读- while(!feof(file))
总是错误的
Please read this - while(!feof(file))
is always wrong
您应该检查scanf
的返回值,而不是检查文件流上的文件结尾指示符.
You should check the return value of scanf
instead of checking the end of file indicator on the file stream.
#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;
}
这篇关于fscanf读取最后一个整数两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!