The 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>
.
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 |
stream.fail() |
Error |
std::ios::badbit |
stream.bad() |
Undefined behaviour |
State of a stream
Here are examples for conditions causing the different states of a stream:
std::ios::eofbit
:
- Reading beyond the last valid character.
std::ios::failbit
:
- False formatted reading.
- Reading beyond the last valid character.
- Opening of a file went wrong.
std::ios::badbit
:
- The size of the stream buffer cannot be adjusted.
- The code conversion of the stream buffer went wrong.
- A part of the stream threw an exception.
stream.fail()
:
- returns whether
std::ios::failbit
orstd::ios::badbit
is set.
The state of a stream can be read and set in the following ways:
stream.clear()
:
Initializes the flags and sets the stream in the goodbit
state.
stream.clear(sta)
:
Initializes the flags and sets the stream sta
state.
stream.rdstate()
:
Returns the current state.
stream.setstate(fla)
:
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, when cannot set it to the goodbit
state.
Get hands-on with 1400+ tech skills courses.