Input And Output Streams

Introduction

  • I/O is provided through the C++ standard library.
  • A stream is a sequence of bytes of infinite length that is used as a buffer to hold data that is waiting to be processed.

Input/Output in C++

  • The istream class is used for input streams. With input streams, the extraction operator (») is used to remove values from the streams.
  • The ostream class is used for output streams. The insertion operator («) is used to put values in the stream.
  • The iostream class can handle both input and output (bidirectional I/O).

Standard Streams in C++

A standard stream is a pre-connected stream provided to a program by it's environment. There are four stream objects in C++:

  1. cin: Tied to the standard input
  2. cout: Tied to the standard output
  3. cerr: Tied to the standard error.
  4. clog: Tied to the standard log.

Examples

Example 1

#include <iostream>
 
int main()
{
    using namespace std;
    // First we'll use the insertion operator on cout to print text to the monitor
    cout << "Enter your age: " << endl;
 
    // Then we'll use the extraction operator on cin to get input from the user
    int nAge;
    cin >> nAge;
 
    if (nAge <= 0)
    {
        // In this case we'll use the insertion operatior on cerr to print an error message
        cerr << "Oops, you entered an invalid age!" << endl;
        exit(1);
    }
 
    // Otherwise we'll use insertion again on cout to print a result
    cout << "You entered " << nAge << " years old" << endl;
 
    return 0;
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.