什么是在这个文件流中抛出异常?
我不明白什么是在我的输入文件流中抛出异常。 我已经完成了几乎确切的事情,没有任何问题。
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;
}
我只打印它现在读取的行来尝试跟踪错误。 它逐行读取文件并打印它们,然后抛出异常。 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时得到一个异常时,库会抛出一个异常。 
当你试图从流中读取,但没有什么可读的时候,读操作将失败(= getline的第二个参数表示的变量中没有插入字符),故障位被设置,在你的情况下抛出一个异常。
  使用while(!ifstream.eof())只有在文件不以换行符结尾时才while(!ifstream.eof()) 。  eofbit仅在流的末尾达到时才被设置,即流的每个内容都被读出。  但是,如果文件以换行符结束,读取操作将失败,而不会在之前设置eofbit。 
可能的解决方案之一:
bool mygetline( std::istream &in, std::string &s )
{
    try {
        return std::getline( in, s );
    }
    catch( std::ifstream::failure & )
    {
         if( !in.eof() ) throw;
         return false;
    }
}
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( mygetline( 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;
}
