如何使用std::getline
函数检查文件结束?如果我使用eof()
,它将不会发出eof
信号,直到我试图读取超出文件结尾。检查字符串中的eof :: getline
28
A
回答
9
只要阅读,然后检查读操作成功:由于多种原因
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))
39
在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)
}
+1
这个答案太棒了。如果你需要错误信息,这是唯一的方法。它真的需要花时间来解决这个问题:http://gehrcke.de/2011/06/reading-files-in-c-using-ifstream-dealing-correctly-with-badbit-failbit-eofbit-and-perror/ – 2011-07-06 11:19:09
相关问题
- 1. 如何检查'\ n'字符使用getline()c字符串
- 2. Getline和EOF
- 3. C++ EOF Getline错误
- 4. 如何检查HTTP客户端的EOF使用fdopen()和getline()
- 5. getline返回空字符串
- 6. 固定字符串与spacebars和EOF检查
- 7. Python:检查字符串中的字符
- 8. 检查字符串中的字符
- 9. 检查字符串的子字符串
- 10. 检查字符串的数字
- 11. 在getline字符串中获取字符串
- 12. 检查字符串中
- 13. 检查字符串
- 14. 检查字符串
- 15. 检查字符串
- 16. 检查字符串
- 17. 检查字符串
- 18. 检查字符串
- 19. 检查字符串
- 20. 检查字符串
- 21. std :: getline和eol vs eof
- 22. getline和一次测试EOF
- 23. C++ getline()和文件EOF
- 24. C++ - getline stdin EOF不工作
- 25. 想法检查字符串的某些字符的字符串检查器?
- 26. 检查字符串包含字符串
- 27. 检查C++中的另一个字符串中的字符串
- 28. 检查字符串中的字符串在javascript中
- 29. 的JavaScript - 检查字符串
- 30. eof字符串,而不是流
这'不建议eof'是真实的,但出于不同的原因。通过EOF读取*完全是*当您想要测试EOF时做什么,所以'eof'在这方面效果很好。 – 2010-02-12 12:03:41