从文本文件读取,直到EOF重复最后一行 [英] Reading from text file until EOF repeats last line

查看:550
本文介绍了从文本文件读取,直到EOF重复最后一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下 C ++ 代码使用 ifstream 对象从文本文件(每行一个)读取整数,直到达到 EOF 。为什么它读取最后一行的整数两次?如何解决此问题?

The following C++ code uses a ifstream object to read integers from a text file (which has one number per line) until it hits EOF. Why does it read the integer on the last line twice? How to fix this?

代码:

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    ifstream iFile("input.txt");	// input.txt has integers, one per line

    while (!iFile.eof())
    {
    	int x;
    	iFile >> x;
    	cerr << x << endl;
    }

    return 0;
}

input.txt

10  
20  
30

输出

10  
20  
30  
30

请注意:我已略过所有错误检查代码,以保持代码段小。上述行为在Windows(Visual C ++),cygwin(gcc)和Linux(gcc)上可见。

Note: I've skipped all error checking code to keep the code snippet small. The above behaviour is seen on Windows (Visual C++), cygwin (gcc) and Linux (gcc).

推荐答案


  • 抓斗10

  • 抓斗20

  • Grab 30

  • Grab EOF

  • Grab 10
  • Grab 20
  • Grab 30
  • Grab EOF

查看第二次到最后一次迭代。你抓住30,然后继续检查EOF。您还没有到达EOF,因为EOF标记尚未读取(二进制,其概念位置刚好在30行之后)。因此,你继续下一次迭代。 x从前一迭代仍为30。现在你从流中读取,你得到EOF。 x保持30,并且ios :: eofbit被提高。你输出到stderr x(这是30,就像在上一次迭代)。

Look at the second-to-last iteration. You grabbed 30, then carried on to check for EOF. You haven't reached EOF because the EOF mark hasn't been read yet ("binarically" speaking, its conceptual location is just after the 30 line). Therefore you carry on to the next iteration. x is still 30 from previous iteration. Now you read from the stream and you get EOF. x remains 30 and the ios::eofbit is raised. You output to stderr x (which is 30, just like in the previous iteration). Next you check for EOF in the loop condition, and this time you're out of the loop.

试试这个:

while (true) {
    int x;
    iFile >> x;
    if( iFile.eof() ) break;
    cerr << x << endl;
}

顺便说一下,代码中还有一个错误。你试过在一个空文件上运行它吗?你得到的行为是完全相同的原因。

By the way, there is another bug in your code. Did you ever try to run it on an empty file? The behaviour you get is for the exact same reason.

这篇关于从文本文件读取,直到EOF重复最后一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆