What are the effects of buffering? Consider Example 9. You might expect the program to print please wait, wait five seconds, and then proceed. It won't necessarily work as you anticipated, however, because the output is buffered.
Example 9
Example 9 clearly demonstrates the effects of buffering.
// exios109.cpp
// A buffered stream object
#include <iostream.h>
#include <time.h>
void main()
{
time_t tm = time( NULL ) + 5;
cout << "Please wait...";
while ( time( NULL ) < tm )
;
cout << "\nAll done" << endl;
}
In order to make the program work sensibly, you must somehow tell cout to empty itself as soon as you want the message to appear. You can tell an ostream object to flush itself by sending it the flush manipulator. To fix the program above, change one line:
cout << "Please wait..." << flush;
This extra step flushes the buffer, which ensures that the message prints before the wait instead of after. You may choose to use endl instead of flush. The endl manipulator flushes the buffer and also outputs a carriage return–linefeed combination.
Note:
The cin object (along with cerr and clog) is normally tied to cout. Thus any use of cin (or of cerr and clog) causes cout to be flushed.