Checking and Handling Stream States
Explore how to inspect and interpret stream state flags in C++ such as good, eof, fail, and bad. Learn techniques to detect and recover from input errors using clear and ignore, and understand when to apply manual checks versus exceptions. This lesson helps you build reliable programs that gracefully handle user input and file I/O errors without crashing.
Writing to the console or reading from a file seems simple until something goes wrong. A file might be missing, a disk might be full, or a user might type "hello" when we request a number. In C++, streams do not crash the program when these issues occur. Instead, they enter an error state and reject subsequent operations. To build resilient software, we must learn to inspect stream state flags, understand what they mean, and recover when recovery is possible.
Understanding stream states
Every stream object in C++ (whether std::cin, std::cout, or a file stream like std::ifstream) maintains a set of internal flags known as iostate. These flags act like dashboard warning lights, indicating the health of the stream.
We can inspect these states using member functions:
good(): This indicates: no errors have occurred, and the stream is ready for I/O.eof(): This indicates the end-of-file. This flag is set when an input operation attempts to read beyond the end of the data source. It is a normal signal that reading is complete.fail(): This indicates a logical error or formatting mismatch. This happens if we try to read an integer, but the stream encounters letters (e.g., "abc"). The stream itself is still intact, but the specific operation failed.bad(): This indicates a critical error that indicates a loss of integrity, such as a hardware failure, memory corruption, or writing to a read-only stream. The stream is likely unusable.
If fail() or bad() is true, the stream halts. It will reject all further attempts to read or write until the issue is addressed.
Example: Triggering and inspecting states
We will use a std::stringstream (an in-memory stream) to simulate input. We will intentionally provide text data when the program ... ...