Working with Streams 635
17
Four standard stream objects are created in every program:cout,cin,cerr, and clog.
Each of these can be “redirected” by many operating systems.
The istreamobject cinis used for input, and its most common use is with the over-
loaded extraction operator (>>). The ostreamobject coutis used for output, and its most
common use is with the overloaded insertion operator (<<).
Each of these objects has a number of other member functions, such as get()and put().
Because the common forms of each of these methods returns a reference to a stream
object, it is easy to concatenate each of these operators and functions.
The state of the stream objects can be changed by using manipulators. These can set the
formatting and display characteristics and various other attributes of the stream objects.
File I/O can be accomplished by using the fstreamclasses, which derive from the stream
classes. In addition to supporting the normal insertion and extraction operators, these
objects also support read()and write()for storing and retrieving large binary objects.
Q&A ....................................................................................................................
Q How do I know when to use the insertion and extraction operators and when
to use the other member functions of the stream classes?
A In general, it is easier to use the insertion and extraction operators, and they are
preferred when their behavior is what is needed. In those unusual circumstances
when these operators don’t do the job (such as reading in a string of words), the
other functions can be used.
Q What is the difference between cerrand clog?
A cerris not buffered. Everything written to cerris immediately written out. This is
fine for errors to be written to the console screen, but might have too high a perfor-
mance cost for writing logs to disk. clogbuffers its output, and thus can be more
efficient, at the risk of losing part of the log if the program crashes.
Q Why were streams created if printf()works well?
A printf()does not support the strong type system of C++, and it does not support
user-defined classes. Support for printf()is really just a carryover from the C
programming language.
Q When would I ever use putback()?
A When one read operation is used to determine whether a character is valid, but a
different read operation (perhaps by a different object) needs the character to be in
the buffer. This is most often used when parsing a file; for example, the C++ com-
piler might use putback().