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
checking for eof in string::getline
提问by assassin
How do I check for end-of-file using the std::getline
function? If I use eof()
it won't signal eof
until 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 eof
member 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";
}
getline
returns the stream so you can write more compactly:
getline
返回流,以便您可以更紧凑地编写:
if(!std::getline(std::cin, str))