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:
ios. Provides extraction operator (>>) and methods like get(), getline(). Defines cin.ios. Provides insertion operator (<<) and methods like put(), write(). Defines cout, cerr, clog.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.
try block.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:
- Explain the C++ Stream Class Hierarchy.
Model Answer:- Draw the diagram with
iosas the base class. - Show
istream(forcin) andostream(forcout) inheriting fromios. - Show
iostreaminheriting from bothistreamandostream(Multiple Inheritance).
- Draw the diagram with
- Explain the keywords
try,catch, andthrowin 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:
- Explain Formatted and Unformatted I/O in C++. Detail at least four manipulators from
<iomanip>with code examples. Discuss Exception Handling with multiplecatchblocks and the catch-all (catch(...)) handler.
Model Answer:- Explain unformatted functions:
get(),put(),getline(), andwrite(). - Explain manipulators:
setw(),setprecision(),setfill(), andendl. - 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*), andcatch(...).
- Explain unformatted functions: