[   ^ to index...   |   next -->   ]

CSE 143/AE : 29 June 2000


C++ I/O streams

A stream is an object that represents a sequence of characters. Input streams (of type istream) can be read, and output streams (of type ostream) written to.

Unlike printf or scanf, use of a stream object does not always require that you provide format specifiers:

fprintf(stdout, "%d %s\n", 5, "foo"); /* C way */ cout << 5 << ' ' << "foo" << endl; // C++ way

One result is that C++ streams are type safe---there is no possibility of attempting to output a character as an integer, or vice versa, without explicit casting.

Standard streams

You are already familiar with at least two of the three standard stream objects. The streams cout, cerr, and cin are objects that are constructed exactly once by the runtime system. The way this happens is deep magic that we need not go into here.

You might ask, "If these streams are objects, they must be instances of a class." Well, they are. However, that class is system-dependent, and the only guarantee is that they will implement the ostream and istream interfaces.

Using input streams

To read input from a stream, we use the >> operator:

int i; char b[30]; cin >> i; // Reads an int from standard input cin >> b; // Reads a "word" from standard input

Any amount of leading whitespace will be skipped. Reading into a char array is interpreted as "read word". A "word" is a sequence of non-whitespace characters.


Last modified: Wed Jun 28 20:39:54 PDT 2000