8.3. Managing the Output BufferEach IO object manages a buffer, which is used to hold the data that the program reads and writes. When we write
os << "please enter a value: ";
the literal string is stored in the buffer associated with the stream os. There are several conditions that cause the buffer to be flushedthat is, writtento the actual output device or file:
Flushing the Output BufferOur programs have already used the endl manipulator, which writes a newline and flushes the buffer. There are two other similar manipulators. The first, flush, is used quite frequently. It flushes the stream but adds no characters to the output. The second, ends, is used much less often. It inserts a null character into the buffer and then flushes it:
cout << "hi!" << flush; // flushes the buffer; adds no data
cout << "hi!" << ends; // inserts a null, then flushes the buffer
cout << "hi!" << endl; // inserts a newline, then flushes the buffer
The unitbuf ManipulatorIf we want to flush every output, it is better to use the unitbuf manipulator. This manipulator flushes the stream after every write:
cout << unitbuf << "first" << " second" << nounitbuf;
is equivalent to writing
cout << "first" << flush << " second" << flush;
The nounitbuf manipulator restores the stream to use normal, system-managed buffer flushing.
Tying Input and Output Streams TogetherWhen an input stream is tied to an output stream, any attempt to read the input stream will first flush the buffer associated output stream. The library ties cout to cin, so the statement
cin >> ival;
causes the buffer associated with cout to be flushed.
The tie function can be called on either istream or an ostream. It takes a pointer to an ostream and ties the argument stream to the object on which tie was called. When a stream ties itself to an ostream, then any IO operation on the stream that called tie flushes the buffer associated with the argument it passed to tie.
cin.tie(&cout); // illustration only: the library ties cin and cout for us
ostream *old_tie = cin.tie();
cin.tie(0); // break tie to cout, cout no longer flushed when cin is read
cin.tie(&cerr); // ties cin and cerr, not necessarily a good idea!
// ...
cin.tie(0); // break tie between cin and cerr
cin.tie(old_tie); // restablish normal tie between cin and cout
An ostream object can be tied to only one istream object at a time. To break an existing tie, we pass in an argument of 0. |