Table of Contents
Input and output streams maintain internal state information that indicates whether stream operations have completed successfully or whether an error has occurred. These state flags help a program detect conditions such as invalid input, reaching the end of a file, or unrecoverable stream errors.
The member functions good(), fail(), eof(), and bad() can be used to examine the current state of a stream after an input or output operation.
Source Code #
#include <iostream>
int main()
{
int number;
std::cout << "Enter an integer: ";
std::cin >> number;
std::cout << "good(): " << std::cin.good() << '\n';
std::cout << "fail(): " << std::cin.fail() << '\n';
std::cout << "eof(): " << std::cin.eof() << '\n';
std::cout << "bad(): " << std::cin.bad() << '\n';
return 0;
}
Output #
Enter an integer: 100
good(): 1
fail(): 0
eof(): 0
bad(): 0
Explanation #
- Input and output streams maintain internal state flags that describe the status of stream operations.
good()returnstrueif no errors have occurred and the stream is ready for further operations.fail()returnstrueif an input or output operation has failed, such as attempting to read a non-numeric value into an integer.eof()returnstruewhen the end of the input source has been reached.bad()returnstrueif a serious stream error has occurred, such as a loss of integrity in the stream buffer.- These member functions return Boolean values, which are displayed as
1fortrueand0forfalseby default. - Checking stream state flags allows a program to detect and handle input and output errors safely.
return 0;terminates the program successfully.