我刚刚在这个答案中发现了一条评论说iostream::eof在循环条件下使用"几乎肯定是错误的".我通常使用类似的东西while(cin>>n)- 我猜是隐式检查EOF,为什么检查eof显式使用while (!cin.eof())错误?
它与scanf("...",...)!=EOF在C中使用有何不同(我经常使用没有问题)?
我知道这种行为的起源,因为它在 SO 的多篇文章中得到了很好的解释,一些值得注意的例子是:
为什么循环条件中的 iostream::eof 被认为是错误的?
它也包含在std::getline标准中:
3) 如果由于某种原因没有提取任何字符(甚至没有被丢弃的分隔符),getline 设置 failbit 并返回。
我的问题是如何处理这种行为,您希望您的流在failbit所有情况下捕获异常,但由于到达eof最后一行为空的文件的,引起的异常除外。有什么明显的我遗漏了吗?
MWE:
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
void f(const std::string & file_name, char comment) {
std::ifstream file(file_name);
file.exceptions(file.failbit);
try {
std::string line;
while (std::getline(file, line).good()) {
// empty getline sets failbit throwing an exception
if ((line[0] != comment) && (line.size() != 0)) {
std::stringstream ss(line);
// …Run Code Online (Sandbox Code Playgroud)