DOC HOME SITE MAP MAN PAGES GNU INFO SEARCH PRINT BOOK
 
iostream examples

Predefined streams

There are four predefined streams, cin, cout, cerr, and clog. The first three are connected to standard input, standard output, and standard error respectively. clog is also connected to standard error but, unlike cerr, clog is buffered. That is, characters are accumulated and written to standard error in chunks. cout is also buffered.

Frequently programs want to use either standard input and output or some external file depending on their command line arguments. One way is to use the predefined streams and assign to them. Assignment of streams is not possible in general but the predefined streams have special types which allow it. The reader is referred to the man pages for a discussion of the semantics of assignment.

A more flexible style is to use a pointer or reference to a stream:

   istream* in = &cin ;
   ...
   if ( infile ) in = new ifstream(infile) ;
   ...
   *in << x  ;

Problems can occur when mixing code that uses iostreams with code that uses stdio. There is no connection between the predefined iostreams and the stdio standard FILEs except that they use the same file descriptors. It is possible to eliminate this problem by calling

   ios::sync_with_stdio()
which will connect the predefined iostreams with the corresponding stdio FILEs. Such connection is not the default because there is a significant performance penalty when the predefined files are made unbuffered as part of the connection.
Next topic: Format control
Previous topic: iostream incore formatting

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