How do you check for and handle stream errors?
Short answer
Streams have state flags: good(), eof() (end of file reached), fail() (format/logic error), and bad() (serious error). A stream is convertible to bool (true if not failed), so you can write while (stream >> x) or if (stream).
Advertisement
AModel answer
Streams have state flags: good(), eof() (end of file reached), fail() (format/logic error), and bad() (serious error). A stream is convertible to bool (true if not failed), so you can write while (stream >> x) or if (stream). Use clear() to reset error flags after handling an error.
int x;
while (std::cin >> x) { /* uses valid x */ }
if (std::cin.fail()) { std::cin.clear(); }Real-world example
A robust input loop stops on bad input using the stream's bool conversion and then clears the error.
Likely follow-ups
- What do fail() and eof() mean? | How do you reset error state?
Related topics