Go to main content
Oracle® Developer Studio 12.6: C++ User's Guide

Exit Print View

Updated: July 2017

13.2 Basic Structure of iostream Interaction

By including the iostream library, a program can use any number of input or output streams. Each stream has some source or sink, which may be one of the following:

  • Standard input

  • Standard output

  • Standard error

  • A file

  • An array of characters

A stream can be restricted to input or output, or a single stream can allow both input and output. The iostream library implements these streams using two processing layers.

  • The lower layer implements sequences, which are simply streams of characters. These sequences are implemented by the streambuf class, or by classes derived from it.

  • The upper layer performs formatting operations on sequences. These formatting operations are implemented by the istream and ostream classes, which have as a member an object of a type derived from class streambuf. An additional class, iostream, is for streams on which both input and output can be performed.

Standard input, output, and error are handled by special class objects derived from class istream or ostream.

The ifstream, ofstream, and fstream classes, which are derived from istream, ostream, and iostream respectively, handle input and output with files.

The istrstream, ostrstream, and strstream classes, which are derived from istream, ostream, and iostream respectively, handle input and output to and from arrays of characters.

When you open an input or output stream, you create an object of one of these types, and associate the streambuf member of the stream with a device or file. You generally do this association through the stream constructor, so you don’t work with the streambuf directly. The iostream library predefines stream objects for the standard input, standard output, and error output, so you don’t have to create your own objects for those streams.

You use operators or iostream member functions to insert data into a stream (output) or extract data from a stream (input), and to control the format of data that you insert or extract.

When you want to insert and extract a new data type—one of your classes—you generally overload the insertion and extraction operators.