int main()
{
int i;
if (cin >> i)
{
//ok
}
else
{
//error
cin.setstate(std::ios_base::goodbit);
}
}
Why can’t I set goodbit through setstate() to clear out the failbit instead of cin.clear()?
Because
setstatecombines the current state with whatever state you’re passing it with a bitwiseOR, ergo the fail bit doesn’t get cleared (set to zero).So assume:
Doing
setstate(okbit)when your state is01is just going to give you11(look ma, the fail bit is still set) so really all you’re doing is screwing up the internal stream state. You should really avoid usingsetstatealtogether.Click for reference.