在string :: getline中检查eof

ass*_*sin 39 c++ file-io getline

如何使用该std::getline功能检查文件结尾?如果我使用eof()它,eof在我尝试读取超出文件结尾之前不会发出信号.

APr*_*mer 53

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


Man*_*uel 12

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

 std::getline(std::cin, str);
 if(!std::cin)
 {
     std::cout << "failure\n";
 }
Run Code Online (Sandbox Code Playgroud)

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

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

getline 返回流,以便您可以更紧凑地编写:

 if(!std::getline(std::cin, str))
Run Code Online (Sandbox Code Playgroud)