Safely read from a stream in a for loop using getline

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

Stream I mean the class inherited from 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 to check also other error conditions, for example

eofbit failbit badbit

But I'm a little confused.

, , - , std::ios_base::failure? ? ?

AFG

+5
2
+2

iostreams . :

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

, .

:

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

:

std::ios_base::failure

std::exception.

, execptions, :

while( std::getline( myStreamObj, line ) ) {
   // process line
}
+6

All Articles