←Back to Subject
Notes
Notes
Study material and explanations
Diagrams
Diagrams
Visualize concepts easily
Mnemonics
Mnemonics
Tricks to remember faster
One Night Prep
One Night Prep
Short and focused revision
Revision
Revision
Quick summary and key points
Important Questions
Important Questions
Practice most relevant questions
Notes

C++ Streams, Formatted I/O & Exception Handling

Study material and explanations for Unit 5

C++ Streams, Formatted I/O & Exception Handling

1. What is a Stream in C++? (In Simple Words)

Think of a Stream like water flowing through a pipe.

In C++, input and output are treated as a continuous flow (stream) of bytes moving between your program and devices:

  • Input Stream: Bytes flowing from an input device (like keyboard or file) into the program (cin >>).
  • Output Stream: Bytes flowing from your program out to a destination (like monitor screen or printer) (cout <<).
                     ┌──────────────────┐
[ Keyboard / File ] ─┤   INPUT STREAM   ├──▶ [ C++ Program in RAM ]
                     └──────────────────┘               │
                                                        ▼
                     ┌──────────────────┐      ┌─────────────────┐
[ Monitor Screen ]  ◀┤  OUTPUT STREAM   ├──────┤   cout << text  │
                     └──────────────────┘      └─────────────────┘

2. C++ Stream Class Hierarchy

C++ organizes all input and output classes into a neat family tree:

C++ Stream Class Inheritance Tree
ios (Root Base Class)
The foundation class. Handles formatting flags and error states for all streams.
istream (Input Stream)
Inherits from ios. Provides extraction operator (>>) and methods like get(), getline(). Defines cin.
ostream (Output Stream)
Inherits from ios. Provides insertion operator (<<) and methods like put(), write(). Defines cout, cerr, clog.
iostream (Both Input & Output)
Inherits from both istream and ostream (Multiple Inheritance) for two-way reading and writing.

3. Unformatted vs. Formatted I/O Operations

A. Unformatted I/O (Raw Character Data)

Reads and writes raw characters without any special formatting or columns:

Function Stream What It Does
cin.get(ch) istream Reads a single character (even spaces and newlines) from keyboard.
cout.put(ch) ostream Prints a single character to the screen.
cin.getline(buf, size) istream Reads a full line of text including spaces until Enter is pressed.
cout.write(buf, size) ostream Prints a specific number of characters from a text buffer.

B. Formatted I/O Using <iomanip> Manipulators

Manipulators change how output is displayed (adding columns, padding characters, or setting decimal places):

#include <iostream>
#include <iomanip> // Must include for setw, setprecision!
using namespace std;

int main() {
    cout << "=== Formatted Account Statement ===" << endl;

    // setw(w): sets column width
    // setfill(ch): fills empty spaces with a custom character
    // fixed + setprecision(n): sets exact decimal places
    cout << left << setw(15) << setfill('.') << "Customer" 
         << right << setw(15) << setfill(' ') << "Balance (INR)" << endl;

    cout << left << setw(15) << setfill('.') << "Rohit Sharma" 
         << right << setw(15) << setfill(' ') << fixed << setprecision(2) << 14500.75 << endl;

    cout << left << setw(15) << setfill('.') << "Priya Joshi" 
         << right << setw(15) << setfill(' ') << fixed << setprecision(2) << 890.00 << endl;

    return 0;
}

4. Exception Handling in C++ (try, catch, throw)

In simple programs, we use if-else to check errors. But for serious errors (like dividing by zero, missing file, or running out of RAM), using too many if-else statements makes code messy.

Exception Handling is a clean way to detect and handle runtime errors so the program does not crash suddenly.

The Three Pillars of Exception Handling
1. try Block
Wrap the risky code here that might cause an error at runtime.
2. throw Statement
When an error occurs, you throw an error message or error code out of the try block.
3. catch Block
Catches the thrown error and displays a friendly message to the user instead of crashing!

5. Practical Code Example: Safe Division Calculator

Dividing by zero in math is undefined. In C++, normal division by zero crashes your program! Here is how we handle it gracefully:

#include <iostream>
using namespace std;

float divide(float a, float b) {
    if (b == 0.0f) {
        // THROW an error message when denominator is zero!
        throw "Error: Division by zero is mathematically impossible!";
    }
    return a / b;
}

int main() {
    float num, den;
    cout << "Enter Numerator and Denominator: ";
    cin >> num >> den;

    // 1. TRY: Run the calculation safely
    try {
        float ans = divide(num, den);
        cout << "Result: " << ans << endl;
    }
    // 2. CATCH: Catch the specific string error message
    catch (const char *msg) {
        cout << "\n[EXCEPTION CAUGHT] " << msg << endl;
        cout << "Please re-run the program with a non-zero denominator." << endl;
    }
    // 3. CATCH-ALL: Fallback for any unknown errors
    catch (...) {
        cout << "[UNKNOWN ERROR] An unexpected error occurred!" << endl;
    }

    cout << "\nProgram continues running normally..." << endl;
    return 0;
}

DAVV Exam Preparation Tips

Frequently Asked 5-Mark Questions:

  1. Explain the C++ Stream Class Hierarchy.
    Model Answer:
    • Draw the diagram with ios as the base class.
    • Show istream (for cin) and ostream (for cout) inheriting from ios.
    • Show iostream inheriting from both istream and ostream (Multiple Inheritance).
  2. Explain the keywords try, catch, and throw in C++.
    Model Answer:
    • try: Marks a block of code to be monitored for errors.
    • throw: Throws an exception when an error occurs.
    • catch: Catches and handles the exception.

Frequently Asked 10-Mark Questions:

  1. Explain Formatted and Unformatted I/O in C++. Detail at least four manipulators from <iomanip> with code examples. Discuss Exception Handling with multiple catch blocks and the catch-all (catch(...)) handler.
    Model Answer:
    • Explain unformatted functions: get(), put(), getline(), and write().
    • Explain manipulators: setw(), setprecision(), setfill(), and endl.
    • Explain the concept of Exception Handling and why it is better than nested if-else.
    • Write out the complete C++ program for division by zero with try, catch(const char*), and catch(...).