iostream examples


Suppose we want to print the variable x. The main mechanism for doing output in the iostream library is the insertion operator <<. This operator is usually called left shift (because that is its built-in meaning for integers) but in the context of iostreams it is called insertion.

   cout << x ;
cout is a predefined ostream and if x has a numeric type (other than char or unsigned char) the insertion operator will convert x to a sequence of digits and punctuation, and send this sequence to standard output. There are different operations depending on the type of x, and the mechanism used to select the operator is ordinary overload resolution. The insertion operator for type t is called the ``t inserter.''

If we have two values we might do:

   cout << x << y ;
which will output x and y, but without any separation between them. To annotate the output we might do:
   cout << "x=" << x
        << ",y=" << y
        << ",sum=" << (x + y) << "\n" ;
This will not only print the values of x, y, and their sum, but labels as well. It uses the string (char*) inserter, which copies zero terminated strings to an ostream.

Notice the parentheses around the sum. These are not needed because the precedence of + is higher than that of <<. But, when using << as insertion, it is easy to forget that C++ is giving it a precedence appropriate to shift. Getting in the habit of always putting in parentheses is a good way to avoid nasty surprises such as having cout<<x&y output x rather than x&y.

The output might look like:


A pointer (void*) inserter is also defined.

   int x = 99 ;
   cout << &x ;
It prints the pointer in hex.

A char inserter is defined:

   char a = 'a' ;
   cout << a << '\n' ;
This prints a and newline.
Next topic: User defined insertion operators
Previous topic: iostream examples

© 2004 The SCO Group, Inc. All rights reserved.
UnixWare 7 Release 7.1.4 - 27 April 2004