C++ 检查 string::getline 中的 eof

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2251433/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:42:42  来源:igfitidea点击:

checking for eof in string::getline

c++file-iogetline

提问by assassin

How do I check for end-of-file using the std::getlinefunction? If I use eof()it won't signal eofuntil I attempt to read beyond end-of-file.

如何使用该std::getline函数检查文件结尾?如果我使用eof()它,eof直到我尝试读取文件末尾之外,它才会发出信号。

回答by AProgrammer

The canonical reading loop in C++ is:

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)
}

回答by Manuel

Just read and then check that the read operation succeeded:

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

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

Since the failure may be due to a number of causes, you can use the eofmember function to see it what happened was actually EOF:

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

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

getlinereturns the stream so you can write more compactly:

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

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