检查 string::getline 中的 eof

Posted

技术标签:

【中文标题】检查 string::getline 中的 eof【英文标题】:checking for eof in string::getline 【发布时间】:2011-01-16 02:58:36 【问题描述】:

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

【问题讨论】:

不推荐 eof 是真的,但出于不同的原因。当您想要测试 EOF 时,读取过去的 EOF正是您所做的,因此 eof 在这方面效果很好。 【参考方案1】:

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)

【讨论】:

这个答案太好了。如果您需要错误消息,这是(唯一的)方法。确实需要时间来解决这个问题:gehrcke.de/2011/06/…【参考方案2】:

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

 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】:

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

string str;
fstream file;

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

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


file.close();

【讨论】:

以上是关于检查 string::getline 中的 eof的主要内容,如果未能解决你的问题,请参考以下文章

使用 read() 函数时检查 EOF

在不移动文件指针的情况下检查文件指针是不是已达到 EOF?

在检查连接的phpmailer时是否捕获了EOF

在 Python 中使用管道文件描述符时如何检查 EOF?

std::cin.getline() 与 std::cin

readObject 的 EOF 异常