In C++, rdstate() gives you the whole error state of a stream in one value. The value is a bit mask: each of the flags eofbit, failbit, and badbit is one bit, and goodbit means no bit is set.
The functions good(), eof(), fail(), and bad() are shortcuts that look at parts of this same value. Use rdstate() when you want to see all the flags together. Include <iostream> to use it.
This is a member function of std::ios. You call it with a dot on a stream object, for example std::cin, std::cout, a file stream, or a std::stringstream. A stream is simply C++'s way to read or write data one piece after another.
Syntax
Call rdstate on a stream. Use the & operator to test one flag.
C++
std::ios::iostate st = in.rdstate();
if (st & std::ios::failbit) {
// failbit is set
}
Call
What it does
in.rdstate()
Returns the current state as an iostate value.
in.rdstate() == std::ios::goodbit
True when no flag is set at all.
in.rdstate() & std::ios::eofbit
Non-zero when eofbit is set. Any other flags are ignored.
Do not print the raw number. Its value is different on different compilers. Test the flags by name instead.
Library declarations
C++
iostate rdstate() const;
Parameters
Parameter
Description
None
rdstate() takes no parameters.
Return Value
Return Value
Description
iostate
A bit mask of the flags that are set. std::ios::goodbit (zero) means that none is set.
C++ Examples
Example 1 — rdstate() on a Healthy Stream
A new string stream has no flags set, so its state equals goodbit.
C++
#include <iostream>
#include <sstream>
int main() {
std::istringstream in("12");
if (in.rdstate() == std::ios::goodbit) {
std::cout << "state: goodbit (no flags)\n";
}
int n = 0;
in >> n;
if (in.rdstate() != std::ios::goodbit) {
std::cout << "state changed after reading " << n << '\n';
}
return 0;
}
Output
state: goodbit (no flags)
state changed after reading 12
How It Works
rdstate() on a new stream returns goodbit, so the first message is printed.
in >> n reads 12 and hits the end of the text, which sets eofbit.
Now rdstate() is not goodbit any more, so the second message appears even though the read worked.
Example 2 — Test Each Flag with &
Write a small helper that prints which flags are set, then use it after a failed read.