std :: getline到达eof时抛出 [英] std::getline throwing when it hits eof
问题描述
std :: getline
在得到 eof
时引发异常。
这就是我的工作方式。
std::getline
throws exception when it gets an eof
.
this is how I am doing.
std::ifstream stream;
stream.exceptions(std::ifstream::failbit|std::ifstream::badbit);
try{
stream.open(_file.c_str(), std::ios_base::in);
}catch(std::ifstream::failure e){
std::cout << "Failed to open file " << _file.c_str() << " for reading" << std::endl;
}
while(!stream.eof()){
std::string buffer = "";
std::getline(stream, buffer);
//process buffer
//I do also need to maintain state while parsing
}
在上面的代码中, getline
抛出异常,因为它获取了 eof
处理这种情况?
In the above code getline
is throwing exception as it gets eof
How to handle this situation ?
std::string buffer = "";
while(std::getline(stream, buffer)){
//also causes getline to hit eof and throw
}
推荐答案
您可以在代码的开始处激活流的异常处理:
You activate the exception handling of your stream at the very beginning of your code:
stream.exceptions(std::ifstream::failbit|std::ifstream::badbit);
现在,如果提取格式数据(例如浮点值,整数或字符串)失败,它将将设置故障位:
Now if the extraction of formatted data such as floating-point values, integers or strings will fail, it will set the failbit:
eofbit indicates that an input operation reached the end of an
input sequence;
failbit indicates that an input operation failed to read the expected
characters, or that an output operation failed to generate the
desired characters.
虽然 getline(stream,buffer)
确实会设置 eofbit
,如果到达末尾文件,它也将设置故障位,因为无法提取所需的字符(一行)。
While getline(stream,buffer)
will indeed set the eofbit
if it reaches the end of a file, it will also set the failbit, since the desired characters (a line) couldn't be extracted.
要么在循环中包裹另一个try-catch-block,要么
Either wrap another try-catch-block around your loop or disable the failbit exception.
#include <iostream>
#include <fstream>
int main(){
std::ifstream stream("so.cc");
stream.exceptions(std::ifstream::failbit|std::ifstream::badbit);
std::string str;
try{
while(std::getline(stream, str));
}catch(std::ifstream::failure e){
std::cerr << "Exception happened: " << e.what() << "\n"
<< "Error bits are: "
<< "\nfailbit: " << stream.fail()
<< "\neofbit: " << stream.eof()
<< "\nbadbit: " << stream.bad() << std::endl;
}
return 0;
}
结果:
Exception happened: basic_ios::clear
Error bits are:
failbit: 1
eofbit: 1
badbit: 0
请注意,同时设置了两者 eofbit
和 failbit
。
Note that both eofbit
and failbit
are set.
另请参见:
-
std :: ios_base :: iostate
- 第27.5.3.1.5节中的表124(请参见上文)
这篇关于std :: getline到达eof时抛出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!