C++ Streams, Formatted I/O & Exception Handling
Stream formatting controls how values appear, such as showing a fee with two decimal places. It does not change the stored amount. Stream failures commonly set state flags, so check the stream or configure exceptions explicitly.
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 <<).
Extraction reads formatted values from an input stream. Insertion sends values to an output stream using its current formatting rules.
- Source Device — Keyboard (standard input) or disk file
- Input Stream (cin) — Flow of byte sequences into program memory
- C++ Program — Computes logic and prepares results
- Output Stream (cout) — Flow of formatted bytes delivered to screen
View diagram · C++ Input/Output Stream Architecture
2. C++ Stream Class Hierarchy
C++ organizes all input and output classes into a neat family tree:
Input and output streams share common stream facilities. File and string streams specialise how characters reach or leave a stream.
- 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.
View diagram · C++ Stream Class Inheritance Tree
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 encloses work that may fail and throw signals an exceptional condition. A matching catch handler decides how to respond.
- 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!
View diagram · The Three Pillars of Exception Handling
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: