# C++ Notes: Summary of Input / Output

## Include files

There are several standard C include files that are commonly used with I/O.

       #include <iostream>  // Defines cin, cout, istream, ostream, ...
       #include <iomanip>   // I/O manipulators (endl, setw, ...)
       #include <fstream>   // File I/O - ifstream and ofstream.
       #include <sstream>   // String streams - istringstream and ostringstream.
       using namespace std;

## Predefined I/O Streams

`cin` | Input stream
`cout` | Output stream
`cerr` | Error message stream
`clog` | Buffered error message stream

# `cin` - Stream Input

`cin` is associated by default to console input.

## Reading numbers in a loop

A typical loop to read numbers would look like this.

    int n;
    int sum = 0;
    while (cin >> n) // reads number into n
        sum = sum + n);
    }

Not only does reading from `cin` do input, it also effectively returns true unless there was an error or EOF.

## EOF

A common way to read until an EOF is with a while loop. The value of the input expression will be true if the reads succeeds, and false if it fails. Two possible reasons for failure would be (1) EOF - End of File, and (2) Bad input (eg, non-numeric characters in a number). An EOF can be made on the keyboard with control-Z on a PC or control-D on a Unix/Macintosh system. Sometimes this must be followed by a carriage return.

## Reading characters from an input stream

Normally, `cin` skips whitespace (blanks, tabs, newlines, etc) when reading. Ignoring whitespace works well for numbers, but it doesn't work if you want all characters including whitespace. The `get` method can be used to read single characters, including whitespace. There are several forms of `get`, but the easiest to use is

    char c;
    while (cin.get(c)) {
        . . . // process the character in c
    }

## Reading entire lines as strings

Here is a typical pattern for reading one line at a time. `getline` reads a line without a terminating newline character into so. Here a `string` is used to hold the line.

    string s;
    while (getline(cin, s)) {
        . . .  // process s
    }

# `cout` - Stream Output

Stream output to the ostream variable cout uses the << (insertion) operator.

    cout << "Hello World" << endl;

# Text File Input

- Text file input: See Reading Text Files
- I/O maniupulators: See summary of I/O Manipulators