相关疑难解决方法(0)

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

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

码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

input.txt:

10  
20  
30
Run Code Online (Sandbox Code Playgroud)

输出:

10  
20  
30  
30
Run Code Online (Sandbox Code Playgroud)

注意:我已跳过所有错误检查代码,以使代码段保持较小.在Windows(Visual C++),cygwin(gcc)和Linux(gcc)上可以看到上述行为.

c++ fstream iostream

117
推荐指数
5
解决办法
27万
查看次数

标签 统计

c++ ×1

fstream ×1

iostream ×1