describes the use of streams for input and output, focusing on formatting techniques.
Streams
Stream classes for input and output
The four standard streams
-
cin Object of class istream to control standard input
-
cout Object of class ostream to control standard output
-
cerr Object of class ostream to control unbuffered error output
-
clog Object of class ostream to control buffered error output
I/O Stream Classes
During the development of C++ a new class-based input/output
system was implemented. This gave rise to the I/O stream
classes, which are now available in a library of their own, the so-called iostream library.
The diagram on the opposite page shows how a so-called class
hierarchy develops due to inheritance. The class ios is
the base class of all other stream classes. It contains the attributes and
abilities common to all streams. Effectively, the ios
class
-
manages the connection to the physical data stream that writes your program's data to a file or outputs the data on screen
-
contains the basic functions needed for formatting data. A number of flags that determine how character input is interpreted have been defined for this purpose.
The istream and ostream classes derived from ios
form a user-friendly interface for stream manipulation. The istream class is used for reading streams and the ostream class is used for writing to streams. The operator
>> is defined in istream
and << is defined in ostream, for example.
The iostream class is derived by multiple
inheritance from istream and ostream and thus offers the functionality of both
classes.
Further stream classes, a file management class, for example,
are derived from the classes mentioned above. This allows the developer to use
the techniques described for file manipulation. These classes, which also
contain methods for opening and closing files, will be discussed in a later
chapter.
Standard Streams
The streams cin and cout, which were mentioned earlier, are instances of the
istream or ostream classes.
When a program is launched these objects are automatically created to read standard input or write to standard
output.
Standard input is normally the keyboard and standard output the
screen. However, standard input and output can be redirected to files. In this
case, data is not read from the keyboard but from a file, or data is not
displayed on screen but written to a file.
The other two standard streams cerr
and clog are used to display messages when errors
occur. Error messages are displayed on screen even if standard output has been
redirected to a file.
0 Comments