Stream Class Hierarchy C++
Stream Class Hierarchy C++
C++ provides a rich set of classes for performing input and output (I/O) operations. The C++
I/O system is built on the stream class hierarchy, which allows efficient handling of various
I/O operations such as reading from files, writing to files, and interacting with standard
input and output devices. This hierarchy is part of the C++ Standard Library and is based on
the iostream library.
1. 1. ios (Base Class) - Base class for all stream classes. Contains common functionality for
input/output operations.
2. 2. istream (Input Stream Class) - Derived from ios. Handles input operations (e.g.,
reading data).
3. 3. ostream (Output Stream Class) - Derived from ios. Handles output operations (e.g.,
writing data).
4. 4. iostream (Input-Output Stream Class) - Derived from both istream and ostream.
Handles both input and output operations.
Derived Classes
The standard I/O streams in C++ are:
5. 1. ifstream (Input File Stream) - Derived from istream. Handles reading from files.
6. 2. ofstream (Output File Stream) - Derived from ostream. Handles writing to files.
7. 3. fstream (File Stream) - Derived from both ifstream and ofstream. Handles both
reading and writing to files.
8. 4. stringstream (String Stream) - Derived from both istream and ostream. Handles
input/output on string objects.
istream - Used for input operations such as reading data from standard input or files.
ostream - Used for output operations such as writing data to standard output or files.
iostream - Handles both input and output operations, useful when both reading and
writing to the same stream.
Example Scenario
In a scenario where you need to read data from a file, perform some processing on the data,
and then write the results to another file, you can use specific stream classes like ifstream
and ofstream to handle file I/O efficiently.
Code Example
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct Student {
string name;
float marks[3];
float average;
};
int main() {
ifstream inputFile("students.txt"); // Reading from a file
ofstream outputFile("results.txt"); // Writing to a file
if (!inputFile || !outputFile) {
cout << "Error opening file!" << endl;
return 1;
}
Student s;
while (inputFile >> s.name >> s.marks[0] >> s.marks[1] >> s.marks[2]) {
s.average = (s.marks[0] + s.marks[1] + s.marks[2]) / 3;
outputFile << "Student: " << s.name << " Average: " << s.average << endl;
}
inputFile.close();
outputFile.close();
return 0;
}
Benefits of Using Stream Classes
Each of these stream classes provides essential functionality for efficient handling of data.
By using the right stream class for input, output, or both, you can ensure optimal I/O
handling in different scenarios.
Conclusion
The stream class hierarchy in C++ is fundamental to handling input and output operations.
It provides a set of specialized classes that handle various types of I/O tasks in an efficient
and organized manner.