48

如何使用该std::getline功能检查文件结尾?如果我使用eof()它不会发出信号eof,直到我尝试读取超出文件结尾的内容。

4

3 回答 3

66

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)
}
于 2010-02-12T12:03:59.050 回答
15

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

 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))
于 2010-02-12T11:44:41.353 回答
1

ifstreampeek()函数,它从输入流中读取下一个字符而不提取它,只返回输入字符串中的下一个字符。因此,当指针位于最后一个字符时,它将返回 EOF。

string str;
fstream file;

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

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

file.close();
于 2021-06-03T14:45:29.833 回答