Introduction to the I/O Stream Classes
This page identifies common input and output tasks you can
perform in C++ programs, and shows how you can accomplish these
tasks using the I/O Stream Library. The tasks are:
- Receiving input from standard input
- Displaying output on standard output or standard error
- Flushing an output stream with the endl and flush
manipulators
- Parsing multiple inputs
- Opening a file for input and reading from the file
- Opening a file for output and writing to the file
- Associating a file with a standard input or output stream
- Using filebuf functions to move through a file
- Defining an input operator for a class type
- Defining an output operator for a class ty[e
- Correcting input stream errors
- Changing the formatting of stram output
- Defining your own format state flags
- Using the strstream classes to accept input from and to
send output to character arrays (strings).
In both C++ and C, input and output
are described in terms of sequences of characters, or streams.
The I/O Stream Classes provide the same facilities in C++
that stdio.h provides in C, but it also has the following
advantages over stdio.h:
- The input or extraction (>>)
operator and the output or insertion (<<) operator
are typesafe. They are also easy to use.
- You can define input and output for your
own types or classes by overloading the input and output
operators. This gives you a uniform way of performing
input and output for different types of data.
- The input and output operators are more
efficient than scanf() and printf(), the analogous C
functions defined in stdio.h.. Both scanf() and printf()
take format strings as arguments, and these format
strings have to be parsed at run time. This parsing can
be time-consuming. The bindings for the I/O Stream output
and input operators are performed at compile time, with
no need for format strings. This can improve the
readability of input and output in your programs, and
potentially the performance as well.