为什么 getline() 在异常掩码未设置为 eofbit 时抛出'std::ios_base::failure'?
Why getline() throws 'std::ios_base::failure' when exception mask is not set to eofbit?
考虑以下代码:
ifstream in;
try {
in.exceptions ( ifstream::failbit | ifstream::badbit );
in.open(pConfLocation);
} catch ( ifstream::failure e ) {
throw std::runtime_error("Can't open configuration filen");
}
vector<string> lns;
string s;
in.clear();
while ( !in.eof() ){
getline( in, s );
boost::algorithm::trim(s);
lns.push_back( s+='n');
}
因此:
- 我为try-catch块的需要设置了以下"异常掩码"(ifstream::failbit | ifstream::badbit)。文件打开时没有问题
- 在while{}块中,我知道在文件的末尾会设置eofbit。但是
异常掩码是所有流对象的内部值指定哪些状态标志在设置。
我没有设置ifstream::eofbit,但无论如何,运行时会出现以下错误:
terminate called after throwing an instance of 'std::ios_base::failure'
what(): basic_ios::clear
The program has unexpectedly finished.
我不能理解这种行为。我试图在.clear()中使用,就在之前,而{},但没有效果。clear()本身设置goodbit,据我所知,"flags必须抛出异常"(参见上面的引用),但当googlebit 如果要删除 它是有效的。 如何使getline()在这种情况下工作in.exceptions ( ifstream::failbit | ifstream::badbit );
问题出在输入迭代中。eofbit
仅在上一次读取达到EOF时设置,而不是在下一次读取将只读EOF时。当后者发生时,failbit
被同时设置。请参阅此处的讨论。
在您的特定情况下,如果文件以换行符结尾(可能是这样),则getline()
读取该换行符并返回。CCD_ 4仍然没有被设置。然后,下一个getline()
直接遇到EOF,根据其文档,"如果函数不提取元素,它将调用setstate(failbit)
。">
相关文章:
- C++ std::locale( "en" ) 在 iOS 上引发异常
- 在瓦尔格林德的泄漏摘要中使用 std::ios::sync_with_stdio(fasle) 打印时获取"still reachable"
- 我需要声明多少次 std::ios::sync_with_stdio(假);在程序中
- 如何提高iOS上的std :: sin功能的精度
- 获取设置故障位的流位置 / std::ios::抛出故障
- std::ios::binary 或 std::ifstream::binary 和类似
- 不同的std::random_shuffle算法导致iOS模拟器单元测试失败
- 为什么我打开一个没有std::ios::binary的文件(std::ifstream)
- 当 std::stringstream 由 ( "some content" , std::ios::in|std::ios::ate) 构造时,tellg() 的预期行为是什么?
- std::ifstream::in 和 std::ios::in 有什么区别?(显然是 C++ 中 std::ifstr
- fstream::open() Unicode 或非 ASCII 字符在 Windows 上不起作用(使用 std::ios::out)
- C++中std::fstream::X和std::ios::X之间的差异
- 调用IOS::exception(..)会导致EOF从C++CLI中的std::getline(..)抛出Interop
- std::ios::openmode的组合,如果文件存在,则截断,但防止创建新文件
- ios:: 在 std::ios::fixed 中的含义
- 在iOS中使用std c++读取文本文件
- 使用std::ios::sync_with_stdio(false)可以比scanf和printf更快
- 为什么我需要在main里面写std::ios::sync_with_stdio
- Crashlytics Fabric错误地处理了从32位平台上的swift ios调用的throw std::异常
- C++如何检查 std::ios 对象的真值