C++ Notes: I/O - Overview

cin and cout can be used for most I/O

One of the great strengths of C++ is that simple I/O is simple. It seems like it should be obviously true, but Java sadly makes simple I/O difficult. To input most values, just use cin (pronounced see-in) and the >> operator. Similarly, for output use cout (pronounced see-out) and the << operator. For example,
int x;
int y;
cin >> x >> y;
cout << "Sum = " << (x+y) << endl;
The input is treated as a stream of characters without regard to spacing or lines. It's also easy to read in a loop.
while (cin >> x) {  // Reads until EOF
   sum += x;
}
See

Reading individual characters and lines

Because the default stream I/O skips whitespace, to read all characters or to read lines, you have to use some different functions. See

Reading text files

Reading text files is very easy. It's basically the same as reading from cin, but you have to define a new file input stream and "open" it with a file name. See

Using strings as source and destination of I/O

You can easily use all of the stream I/O capabilities to "read" and "write" using strings. This isn't so commonly done, but it can be very useful. See

Formatting output

The I/O manipulators can be used to format your output, eg, to choose field widths and number of decimals printed. See