safe reading from a stream in a for loop using getline

I want to read from a stream using std::getline inside a for loop.

The stream I mean is a class inherited from the std::basic_iostream .

std::string line;            
for(;;){
      try{
          std::getline( myStreamObj, line );
          if( line != "" ){
              std::cout << line << std::endl;
          }
      }
      catch( std::ios_base::failure& ex ){
          std::cout << ex.what() << std::endl;
      }
  }

I want also to check against other error conditions like

eofbit failbit badbit

But I am bit confused about it.

If some of the conditions settings these 3 flags is met is any exception thrown like std::ios_base::failure ? How to handlse these 3 cases? Do I have to do checkings other ways?

Thanks AFG


If you want to capture the errors via exceptions you need to set it using ios::exception. Otherwise an exception will not be thrown. You can check out the documentation here: http://www.cplusplus.com/reference/iostream/ios/exceptions/.

You can also explicitly call ios::fail(), ios::bad() or ios::eof(). Docs here: http://www.cplusplus.com/reference/iostream/ios/


The iostreams by default do not throw exceptions when errors occur. If you want to enable them:

cout.execeptions( std::ios::badbit );

would enable exceptions if badbit is set.

To enable them all:

cout.execeptions( std::ios::badbit 
                   | std::ios::eofbit 
                   | std::ios::failbit );

The exceptions thrown are of type:

std::ios_base::failure

which is derived from std::exception .

In general though, it is easier not to use execptions, but to use constructs like:

while( std::getline( myStreamObj, line ) ) {
   // process line
}
链接地址: http://www.djcxy.com/p/61302.html

上一篇: 迭代器会导致ifstream.fail()被设置

下一篇: 使用getline在for循环中从流中安全读取数据