Dip*_*Sen 6 c++ fstream getline eof
std::getline当它获得一个时抛出异常eof.这就是我的表现.
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
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码getline中抛出异常,因为它获得了eof
如何处理这种情况?
std::string buffer = "";
while(std::getline(stream, buffer)){
//also causes getline to hit eof and throw
}
Run Code Online (Sandbox Code Playgroud)
Zet*_*eta 13
您可以在代码的最开头激活流的异常处理:
stream.exceptions(std::ifstream::failbit|std::ifstream::badbit);
Run Code Online (Sandbox Code Playgroud)
现在,如果提取格式化数据(如浮点值,整数或字符串)将失败,它将设置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)确实会设置eofbitif到达文件的末尾,但它也会设置failbit,因为无法提取所需的字符(一行).
在循环周围包装另一个try-catch-block或禁用failbit异常.
#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;
}
Run Code Online (Sandbox Code Playgroud)
结果:
Exception happened: basic_ios::clear Error bits are: failbit: 1 eofbit: 1 badbit: 0
请注意,这两个 eofbit和failbit设置.
也可以看看:
std::ios_base::iostate