从文本文件中读取直到 EOF 重复最后一行

Reading from text file until EOF repeats last line(从文本文件中读取直到 EOF 重复最后一行)

本文介绍了从文本文件中读取直到 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
  • 抢30
  • 获取EOF

查看倒数第二次迭代.你抓住了 30,然后继续检查 EOF.您尚未到达 EOF,因为尚未读取 EOF 标记(二进制"而言,其概念位置就在 30 行之后).因此,您继续进行下一次迭代.x 仍然是前一次迭代的 30.现在您从流中读取并获得 EOF.x 保持 30 并且 ios::eofbit 被提升.您输出到 stderr x (它是 30,就像在上一次迭代中一样).接下来您检查循环条件中的 EOF,这一次您退出了循环.

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 重复最后一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:从文本文件中读取直到 EOF 重复最后一行

基础教程推荐