State of the Stream

Are there tools we can use in C++ which allow us to check the current condition of the stream? Flags answer this question.

Flags represent the state of the stream stream. The methods for dealing with these flags need the header <iostream>. Flags representing the state of a stream are:

Flag Query of the flag Description
std::ios::goodbit stream.good() No bit set
std::ios::eofbit stream.eof() end-of-file bit set
std::ios::failbit Error
std::ios::badbit stream.bad() Undefined behaviour

State of a stream

Here are examples of conditions causing the different states of a stream:


  • Reading beyond the last valid character.


  • False formatted reading.
  • Reading beyond the last valid character.
  • Opening of a file went wrong.


  • Size of the stream buffer cannot be adjusted.
  • Code conversion of the stream buffer went wrong.
  • A part of the stream threw an exception.

  • returns whether std::ios::failbit or std::ios::badbit is set.

The state of a stream can be read and set.

Initializes the flags and sets the stream in the goodbit state.

Initializes the flags and set the stream into sta state.

Returns the current state.

Sets the additional flag fla.

Operations on a stream only work if the stream is in the goodbit state. If the stream is in the badbit state you cannot set it to goodbit state.

Get hands-on with 1000+ tech skills courses.