The GNU C++ Iostream Library



Chapter 2: Operators and Default Streams

The GNU iostream library, libio, implements the standard input and output facilities for C++. These facilities are roughly analogous (in their purpose and ubiquity, at least) with those defined by the C stdio functions.

Although these definitions come from a library, rather than being part of the ``core language'', they are sufficiently central to be specified in the latest working papers for C++.

You can use two operators defined in this library for basic input and output operations. They are familiar from any C++ introductory textbook: << for output, and >> for input. (Think of data flowing in the direction of the ``arrows''.)

These operators are often used in conjunction with three streams that are open by default:


Variable:  ostream cout

The standard output stream, analogous to the C stdout.

Variable:  istream cin

The standard input stream, analogous to the C stdin.

Variable:  ostream cerr

An alternative output stream for errors, analogous to the C stderr.

For example, this bare-bones C++ version of the traditional ``hello'' program uses << and cout:

#include <iostream.h>

int main(int argc, char **argv)
{
  cout << "Well, hi there.\n";
  return 0;
}

Casual use of these operators may be seductive, but---other than in writing throwaway code for your own use---it is not necessarily simpler than managing input and output in any other language. For example, robust code should check the state of the input and output streams between operations (for example, using the method good). See States. You may also need to adjust maximum input or output field widths, using manipulators like setw or setprecision.


Operator:  ostream <<

Write output to an open output stream of class ostream. Defined by this library on any object of a C++ primitive type, and on other classes of the library. You can overload the definition for any of your own applications' classes.

Returns a reference to the implied argument *this (the open stream it writes on), permitting statements like

cout << "The value of i is " << i << "\n";

Operator:  istream >>

Read input from an open input stream of class istream. Defined by this library on primitive numeric, pointer, and string types; you can extend the definition for any of your own applications' classes.

Returns a reference to the implied argument *this (the open stream it reads), permitting multiple inputs in one statement.



Translated 02/24/96 by Rance Necaise. Original texi file by Bothner and Pesch.