Usually, input and output can be handled more efficiently by using a buffer. A
Figure 17.2. A stream with a buffer.
Keyboard input provides one character at a time, so in that case, a program doesn’t need a buffer to help match different data transfer rates. However, buffered keyboard input allows the user to back up and correct input before transmitting it to a program. A C++ program normally flushes the input buffer when you press Enter. That’s why the examples in this book don’t begin processing input until you press Enter. For output to the display, a C++ program normally flushes the output buffer when you transmit a newline character. Depending on the implementation, a program may flush input on other occasions, too, such as at impending input. That is, when a program reaches an input statement, it flushes any output currently in the output buffer. C++ implementations that are consistent with ANSI C should behave in that manner.
Streams, Buffers, and the iostream File
The business of managing streams and buffers can get a bit complicated, but including the iostream (formerly iostream.h) file brings in several classes designed to implement and manage streams and buffers for you. The C++98 version of C++ I/O defines class templates in order to support both char and wchar_t data. C++11 adds char16_t and char32_t specializations. By using the typedef facility, C++ makes the char specializations of these templates mimic the traditional non-template I/O implementation. Here are some of those classes (see Figure 17.3):
• The streambuf class provides memory for a buffer, along with class methods for filling the buffer, accessing buffer contents, flushing the buffer, and managing the buffer memory.
• The ios_base class represents general properties of a stream, such as whether it’s open for reading and whether it’s a binary or a text stream.
• The ios class is based on ios_base, and it includes a pointer member to a streambuf object.
• The ostream class derives from the ios class and provides output methods.
• The istream class derives from the ios class and provides input methods.
• The iostream class is based on the istream and ostream classes and thus inherits both input and output methods.
Figure 17.3. Some I/O classes.
To use these facilities, you use objects of the appropriate classes. For example, you use an ostream object such as cout to handle output. Creating such an object opens a stream, automatically creates a buffer, and associates it with the stream. It also makes the class member functions available to you.
Redefining I/O