---
title: 2.12 Stream State Flags
description: 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,…
url: "https://edcret.in/docs/cpp-programming/input-and-output-cplusplus/2-12-stream-state-flags/"
updated: "2026-07-28"
category: C++ Programming / Input and Output
---

# 2.12 Stream State Flags

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()` returns `true` if no errors have occurred and the stream is ready for further operations.
- `fail()` returns `true` if an input or output operation has failed, such as attempting to read a non-numeric value into an integer.
- `eof()` returns `true` when the end of the input source has been reached.
- `bad()` returns `true` if 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 `1` for `true` and `0` for `false` by default.
- Checking stream state flags allows a program to detect and handle input and output errors safely.
- `return 0;` terminates the program successfully.
