top of page
Writer's picturecompnomics

C++ Stream Classes: Input/Output Operations


C++ provides a powerful and flexible input/output (I/O) system based on stream classes. These classes allow you to perform various operations on input and output streams, such as reading from files, writing to files, and interacting with the console.


Key Stream Classes

  1. istream:

    • Represents an input stream.

    • Used for reading data from input sources like files or the console.

    • Common operations: >>, get(), getline(), ignore(), peek().

  2. ostream:

    • Represents an output stream.

    • Used for writing data to output destinations like files or the console.

    • Common operations: <<, put(), write(), flush().

  3. iostream:

    • Combines istream and ostream functionalities.

    • Used for both input and output operations.


Standard Streams

C++ provides three standard stream objects:

  • cin: Standard input stream (usually the keyboard)

  • cout: Standard output stream (usually the console)

  • cerr: Standard error stream (usually the console)


Example: Reading and Writing to Files

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {
    // Writing to a file
    ofstream outfile("output.txt");
    outfile << "Hello, world!" << endl;
    outfile.close();

    // Reading from a file
    ifstream infile("output.txt");
    string line;
    while (getline(infile, line)) {
        cout << line << endl;
    }
    infile.close();

    return 0;
}

Key Points:

  • Stream Formatting: Use iomanip to format output, including setting precision, width, and fill characters.

  • Error Handling: Check for errors using fail() and bad() functions.

  • File I/O Modes: Control file access modes (read, write, append) using the ios flags.

  • Buffering: Stream objects use buffers to improve performance. You can control buffering using setvbuf().


By understanding and effectively using C++ stream classes, you can perform a wide range of input/output operations in your programs.

36 views0 comments

Recent Posts

See All

Comments

Rated 0 out of 5 stars.
No ratings yet

Add a rating
bottom of page