"The input operation has another side effect: It causes our prompt, which asks for the user's
name, to appear on the computer's output device. In general, the input-output library saves
its output in an internal data structure called a buffer, which it uses to optimize output
operations. Most systems take a significant amount of time to write characters to an output
device, regardless of how many characters there are to write. To avoid the overhead of
writing in response to each output request, the library uses the buffer to accumulate the
characters to be written, and flushes the buffer, by writing its contents to the output
device, only when necessary. By doing so, it can combine several output operations into a
single write.
There are three events that cause the system to flush the buffer. First, the buffer might be
full, in which case the library will flush it automatically. Second, the library might be asked
to read from the standard input stream. In that case, the library immediately flushes the
output buffer without waiting for the buffer to become full. The third occasion for flushing
the buffer is when we explicitly say to do so.
When our program writes its prompt to cout , that output goes into the buffer associated
with the standard output stream. Next, we attempt to read from cin . This read flushes the
cout buffer, so we are assured that our user will see the prompt.
Our next statement, which generates the output, explicitly instructs the library to flush the
buffer. That statement is only slightly more complicated than the one that wrote the prompt.
Here we write the string literal "Hello, " followed by the value of the string variablename , and finally by std::endl . Writing the value of std::endl ends the line of output,and then flushes the buffer, which forces the system to write to the output stream
immediately.
Flushing output buffers at opportune moments is an important habit when you are writing
programs that might take a long time to run. Otherwise, some of the program's output
might languish in the system's buffers for a long time between when your program writes it
and when you see it"
Partager