Unit VII - I/O Stream in C++

Topic 1: Input/Output (Stream-based I/O, Class Hierarchy, Testing Stream Errors)

Theoretical Explanation

C++ handles input and output through streams, which are sequences of bytes transferred between the program and devices (e.g., console, files). Key subtopics include:

Example Program: Stream-based I/O with Error Testing

This program demonstrates console I/O with error checking for invalid input.

#include <iostream>
using namespace std;

int main() {
    int age;
    cout << "Enter your age: ";
    cin >> age;

    // Test for input errors
    if (cin.fail()) {
        cout << "Error: Invalid input. Please enter a number." << endl;
        cin.clear(); // Clear error state
        cin.ignore(10000, '\\n'); // Discard invalid input
    } else {
        cout << "You entered: " << age << endl;
    }

    // Check stream state
    if (cin.good()) {
        cout << "Stream is in a good state." << endl;
    }

    return 0;
}

Explanation:

Topic 2: Unformatted Input/Output

Theoretical Explanation

Unformatted I/O involves reading or writing raw data without specific formatting. Functions include: