In C++, bad() returns true when the stream has set its badbit. This flag means something went seriously wrong, such as a damaged device or a lost connection to the buffer.
Do not mix it up with fail(). A simple typing mistake, like letters where a number is expected, only sets failbit. bad() stays false for such ordinary problems. 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 bad on any stream. It takes no arguments.
C++
bool broken = file.bad();
if (std::cin.bad()) {
std::cerr << "stream is damaged\n";
}
Call
What it does
file.bad()
Returns true only when badbit is set.
s.setstate(std::ios::badbit)
Sets the flag by hand. This is mostly useful for testing.
s.clear()
Clears all flags, including badbit.
Most beginner programs never see badbit. When a read fails, look at fail() and eof() first.
Library declarations
C++
bool bad() const;
Parameters
Parameter
Description
None
bad() takes no parameters.
Return Value
Return Value
Description
true
badbit is set. The stream lost its integrity.
false
badbit is not set. Other flags such as failbit may still be set.
C++ Examples
Example 1 — bad() After a Typing Mistake
Read a number from letters and compare bad() with fail().
start: not bad
after setstate: bad
good(): no
after clear: not bad
How It Works
A new std::stringstream starts with all flags clear, so bad() is false.
setstate(std::ios::badbit) raises the flag. Now bad() is true and good() is false.
clear() with no argument sets the state back to goodbit, which removes badbit again.
Frequently Asked Questions
bad() returns true when badbit is set. It means the stream had a serious error, such as a hardware problem or a broken buffer, and the stream may have lost data.
fail() is true for ordinary problems like wrong input or a file that cannot be opened (failbit), and also when badbit is set. bad() is true only for badbit, the serious case.
No. Typing letters when a number is expected sets only failbit. badbit stays clear.
You can call clear() to reset the flags, but the underlying problem may still exist. For example, a disk error will probably happen again.
Usually not. Check the result of the read itself, for example if (cin >> x), or use fail() and eof(). Check bad() when you handle files and need to tell a real I/O error from a normal end of file.