我的代码在捕获块中处理了正确的 eof 后到达 eof 时会引发 basic_ios::clear ?
My code raise basic_ios::clear when it reach eof though after proper eof handled in catch block?
我的代码在到达 eof 时设置 std::failbit 并抛出异常 如何跳过 EOF 异常
在 catch 块中,我检查并跳过异常是否是因为 eof 但它不好。
请建议如何在下面的代码中跳过 EOF 异常
std::ifstream in
std::string strRead;
in.exceptions ( std::ifstream::failbit | std::ifstream::badbit );
try
{
while (getline( in,strRead))
{
//reading the file
}
catch(std::ifstream::failure & exce)
{
if(! in.eof()) // skip if exception because of eof but its not working?
{
cout<<exce.what()<<endl;
return false;
}
}
catch(...)
{
cout("Unknow exception ");
return false;
}
经过私下讨论,我们设法为他的问题找到了解决方案:当达到 eof 时,getline(in, strRead)
会将故障位设置为 1(正常行为(,他不希望这种情况发生。我们同意使用其他方法来读取文件的内容:
std::ifstream in(*filename*); // replace *filename* with actual file name.
// Check if file opened successfully.
if(!in.is_open()) {
std::cout<<"could not open file"<<std::endl;
return false;
}
in.seekg(0, std::ios::end);
std::string strRead;
// Allocate space for file content.
try {
strRead.reserve(static_cast<unsigned>(in.tellg()));
} catch( const std::length_error &le) {
std::cout<<"could not reserve space for file"<<le.what()<<std::endl;
return false;
} catch(const std::bad_alloc &bae) {
std::cout<<"bad alloc occurred for file content"<<bae.what()<<std::endl;
return false;
} catch(...) {
std::cout<<"other exception occurred while reserving space for file content"<<std::endl;
return false;
}
in.seekg(0, std::ios::beg);
// Put the content in strRead.
strRead.assign(std::istreambuf_iterator<char>(in),
std::istreambuf_iterator<char>());
// Check for errors during reading.
if(in.bad()) {
std::cout<<"error while reading file"<<std::endl;
return false;
}
return true;
禁用故障位将是最好的方法,否则每次在使用 getline(( 时都会收到此异常
相关文章:
- 如何确定我已使用非编码文件到达 EOF?
- 如何在Visual Basic中使用矩形函数OpenGL绘制矩形
- std::ifstream::read 不会读取所有 512 字节,并设置 EOF 和失败位
- 这是 basic.def.odr 部分的缺陷吗?
- 而(!inputfile.eof())只读取第一行?
- EOF有更安全的替代方案吗?它在我的情况下不起作用
- "错误 C0000:语法错误,令牌"<EOF>"处出现意外$end,并且不确定
- 如何在 EOF 之前从文件中读取并将其放入字符串中?
- 如何在从文件中读取整数时使用 file.eof()?
- "eof"可以设置为流吗?
- 吃完 EOF 后重复使用 std::cin
- 文件处理,eof() 定义
- 未定义的对象(〔basic.life〕/8):为什么允许引用重新绑定(和常量修改)
- std::cin 在读取 EOF 并清除后不再读取
- 为什么 EOF 在循环扫描期间没有终止?
- cin.clear()是否保留EOF
- 而(getline(fin,str)){}即使在到达eof之后仍在处理数据
- 通过终端在文件中输入时检测EOF(文件结束)时出现问题
- 为什么如果我从键盘输入EOF克里昂不要在运行窗口打印程序的输出?
- 为什么"cin"在EOF之后不再wοrk?