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

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

【问题讨论】:

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

标签: c++ file-io getline


【解决方案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();
    

    【讨论】:

      猜你喜欢
      • 2019-11-13
      • 1970-01-01
      • 1970-01-01
      • 2011-01-21
      • 2021-03-04
      • 1970-01-01
      • 2012-06-18
      • 2019-04-23
      • 2016-11-19
      相关资源
      最近更新 更多