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 |
stream.fail() |
Error |
std::ios::badbit |
stream.bad() |
Undefined behaviour |
State of a stream
Here are examples of 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
:
- Size of the stream buffer cannot be adjusted.
- 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.
stream.clear()
:
Initializes the flags and sets the stream in the goodbit
state.
stream.clear(sta)
:
Initializes the flags and set the stream into 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 you cannot set it to goodbit
state.
Get hands-on with 1400+ tech skills courses.