In C++, clear() sets the error state of a stream. With no argument it resets the state to goodbit, which removes failbit, eofbit, and badbit.
Despite its name, it does not erase any data and it does not empty the input buffer. It only fixes the flags. 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 clear on a stream. You can pass a state value, but most programs call it with no arguments.
C++
std::cin.clear(); // back to goodbit
std::cin.clear(std::ios::eofbit); // set exactly this state
Call
What it does
std::cin.clear()
Resets all flags to goodbit. cin accepts reads again.
s.clear(std::ios::eofbit)
Replaces the state with only eofbit. It does not add to the old flags.
std::cin.ignore(1000, '\n')
Usually written right after clear() to remove the bad characters.
The standard fix for bad input is a pair: cin.clear() and then cin.ignore(). Use them in that order.
Library declarations
C++
void clear(iostate state = goodbit);
Parameters
Parameter
Description
state
Optional. The new state value. The default is std::ios::goodbit, which means no flags. Any value you pass replaces the old state.
Return Value
Return Value
Description
Nothing
clear() returns void. The state of the stream is changed.
C++ Examples
Example 1 — Read Again After a Failure
Fail on a word, clear the flags, skip the word, and read the number behind it.
C++
#include <iostream>
#include <sstream>
#include <string>
int main() {
std::istringstream in("abc 5");
int n = 0;
in >> n;
std::cout << "first read failed: " << (in.fail() ? "yes" : "no") << '\n';
in.clear();
std::string skip;
in >> skip;
in >> n;
std::cout << "n = " << n << '\n';
return 0;
}
Output
first read failed: yes
n = 5
How It Works
in >> n fails on the letters abc. They stay in the stream and failbit is set.
clear() removes the flag. Then in >> skip reads abc into a string and gets it out of the way.
The next in >> n finds 5 and works. Without clear() this last read would fail without even trying.
Example 2 — clear() with a State Argument
Passing a flag replaces the state. This is handy for tests.