Search code examples
c++undefined-behavioristreamstd

Is calling operator>> on a istream in a fail/bad state undefined behavior?


int main()
{
   std::ifstream istr( "foo.txt" );
   int a, b;
   istr >> a;
   istr >> b;
}

Suppose the line istr >> a sets the stream's failbit or errorbit. Is it defined behavior to subsequently call istr >> b?


Solution

  • Yes, that's well-defined. The first stage of formatted input is to construct a sentry object, which checks the state of the stream. If the state is not good, then the extraction does nothing.

    It would be undefined behaviour to use the value of b afterwards, since it would still be uninitialised.