带有额外最终迭代的文件echo循环

HC.*_*HC. 1 c++ file-io while-loop

为什么在此代码完成时会获得额外的迭代(额外的行打印)?EOF需要额外的换行吗?我不想添加额外/特殊字符来标记EOF.

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

int main(){  
    ifstream infile("dictionary.txt"); // one word per line  
    string text;  
    while(infile){  
        infile >> text;  
        cout << text << endl;  
    }  
    infile.close();  
    return 0;  
}  
Run Code Online (Sandbox Code Playgroud)

Mic*_*ker 6

尝试

while(infile>>text) cout << text << endl;
Run Code Online (Sandbox Code Playgroud)

代替.


Ros*_*ith 6

您尝试读取之前,输入流不会检测到文件结尾.当您读取文件中的最后一个单词时,输入流仍然有效; 在下一个循环中,infile >> text尝试读取过去的EOF并失败,但无论如何仍然执行下一行.

循环应如下所示:

while (infile >> text)
    cout << text << endl;
Run Code Online (Sandbox Code Playgroud)

这样EOF将在尝试写入输出之前被检测到.