iostream examples

Miscellaneous formatting

As a precaution against looping, zero width fields are considered a bad format by the extractors. So if the next character is whitespace and ios::skipws is not set, the arithmetic extractors will set an error bit.

The number of significant digits inserted by the floating point (double) inserter is controlled by the precision state variable. The details of the conversion are further controlled by certain flags. The reader is referred to the man page for more details.

It is good practice to flush ostreams appropriately. The flush and endl manipulators make it relatively easy to do so. Yet, there are circumstances in which some automatic flushing is appropriate. This is supported by the ostream* valued state variable tie. If i.tie is non-null and an istream needs more characters, the ostream pointed at by tie is flushed. Initially cin is tied in this fashion to cout so that attempts to get more characters from standard input result in flushing standard output. This seems to handle most interactive programs reasonably well without imposing a large performance penalty on non-interactive programs and without creating different behavior when programs are connected to pipes rather than directly to a terminal. (Programs that won't work when their input or output is connected to a pipe are one of the author's pet peeves.) The overheads implied by tying are relatively small when compared with ``big'' extractors (such as the arithmetic ones) but may be large when single character operations are being performed. For this reason it is sometimes a good idea to break the tie by setting the state variable to 0. For example:

   char c ;
   // break the tie to improve performance of get.
   cin.tie(0) ;
   while ( cin.get(c) ) cout.put(c) ;

Next topic: Manipulators
Previous topic: Conversion base

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