在string::getline中检查文件结尾(eof)

54

我如何使用 std::getline 函数检查文件结尾? 如果我使用 eof() 函数,它在我尝试读取超出文件结尾后才会发出 eof 信号。


“eof”不被推荐使用是真的,但原因不同。当你想测试EOF时,读取EOF之后的内容是正好的操作,所以在这方面,“eof”的效果很好。 - Konrad Rudolph
3个回答

72

C++中的规范读取循环是:

while (getline(cin, str)) {

}

if (cin.bad()) {
    // IO error
} else if (!cin.eof()) {
    // format error (not possible with getline but possible with operator>>)
} else {
    // format error (not possible with getline but possible with operator>>)
    // or end of file (can't make the difference)
}

1
这个答案非常棒。如果你需要错误信息,这是唯一的方法。它确实需要时间来弄清楚:http://gehrcke.de/2011/06/reading-files-in-c-using-ifstream-dealing-correctly-with-badbit-failbit-eofbit-and-perror/ - Dr. Jan-Philip Gehrcke

17

读取后检查读取操作是否成功:

 std::getline(std::cin, str);
 if(!std::cin)
 {
     std::cout << "failure\n";
 }

由于失败可能是由多种原因引起的,因此您可以使用eof成员函数来查看实际发生的是否为EOF:

 std::getline(std::cin, str);
 if(!std::cin)
 {
     if(std::cin.eof())
         std::cout << "EOF\n";
     else
         std::cout << "other failure\n";
 }

getline 返回流,这样可以更紧凑地编写代码:

 if(!std::getline(std::cin, str))

3

ifstream有一个peek()函数,它可以从输入流中读取下一个字符而不将其提取出来,只是返回输入字符串中的下一个字符。 因此,当指针位于最后一个字符时,它将返回EOF。

string str;
fstream file;

file.open("Input.txt", ios::in);

while (file.peek() != EOF) {
    getline(file, str);
    // code here
}

file.close();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接