什么是抛出此文件流中的异常? [英] What Is Throwing The Exception In This File Stream?

查看:281
本文介绍了什么是抛出此文件流中的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白什么是抛出异常在这里与我的输入文件流。我已经做了几乎确切的事情没有任何问题。

  std :: string accnts_input_file =absolute_path / account_storage.txt 
std :: string strLine;
std :: ifstream istream;
istream.exceptions(std :: ifstream :: failbit | std :: ifstream :: badbit);

try
{
istream.open(accnts_input_file.c_str());

while(std :: getline(istream,strLine))
{
std :: cout< strLine< '\\\
';
}

istream.close();
}
catch(std :: ifstream :: failure& e)
{
std :: cerr< 打开/读取/关闭文件时出错< '\\\
'
<< e.what()
<< std :: endl;
}

我只打印它现在读取的行,尝试跟踪错误。它读取文件,逐行并打印它们,然后它抛出异常。异常说basic_ios :: clear,我不明白。我认为是ifstream :: failbit是抛出异常,因为当我只设置ifstream :: badbit它不抛出异常,但我不能弄清楚为什么。我也尝试过'while(!istream.oef())'和大多数其他方法,而不是'while(std :: getline(istream,strLine))',但我得到相同的错误。 >

我相信这可能是明显的我失踪,但任何帮助将不胜感激。感谢

解决方案

std :: getline 参考


。 ..

a)输入文件结束条件,在这种情况下,getline集 eofbit

。 ..

3)如果没有任何原因(即使是丢弃的分隔符)没有提取字符,getline设置 failbit 并返回。 >

这意味着在文件结束时,函数设置两者 eofbit failbit 。由于您在 failbit 设置时要求获得异常,因此库将抛出异常。


I don't understand what is throwing the exception here with my input file stream. I have done almost the exact thing before without any problems.

std::string accnts_input_file = "absolute_path/account_storage.txt";
std::string strLine;
std::ifstream istream;
istream.exceptions( std::ifstream::failbit | std::ifstream::badbit );

try
{
    istream.open( accnts_input_file.c_str() );

    while( std::getline( istream, strLine ) )
    {
        std::cout << strLine << '\n';
    }

    istream.close();
}
catch( std::ifstream::failure &e )
{
    std::cerr << "Error opening/reading/closing file" << '\n'
              << e.what()
              << std::endl;
}

I only have it printing the line it reads right now to try and track the error. It reads the file, line by line and prints them, then it throws the exception. The exception says basic_ios::clear, which i don't understand. I think it is ifstream::failbit that is throwing the exception, because when I only set ifstream::badbit it doesn't throw an exception, but I can't figure out why. I've also tried 'while( !istream.oef() )', and most other methods, instead of 'while( std::getline( istream, strLine ) )', but i keep getting the same error.

I'm sure it's probably something obvious I'm missing, but any help would be appreciated. Thanks

解决方案

From this std::getline reference:

...
a) end-of-file condition on input, in which case, getline sets eofbit.
...
3) If no characters were extracted for whatever reason (not even the discarded delimiter), getline sets failbit and returns.

That means that on end of file condition, the function sets both eofbit and failbit. And as you asked to get an exception when failbit is set, the library throws an exception.

这篇关于什么是抛出此文件流中的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆