Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

1 Answer
Samual Sam

The buffer flush is used to transfer of computer data from one temporary storage area to computers permanent memory. If we change anything in some file, the changes we see on the screen are stored temporarily in a buffer.

In C++, we can explicitly have flushed to force the buffer to be written. If we use std::endl, it adds one new line character, and also flush it. If this is not used, we can explicitly use flush. In the following program at first no flush is used. Here we are trying to print the numbers, and wait for one seconds. For the first, we cannot see any output until all of the numbers are stored into the buffer, then the numbers will be displayed in one shot.

In the second example, each number will be printed, then wait for some time then print the next one again. So for using the flush, it sends the output to the display.

Example

#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
main() {
   for (int x = 1; x <= 5; ++x) {
      cout >> x >> " ";
      this_thread::sleep_for(chrono::seconds(1)); //wait for 1 second
   }
   cout >> endl;
}

Output

1 2 3 4 5
output will be printed at once after waiting 5 seconds

Example

#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
main() {
   for (int x = 1; x <= 5; ++x) {
      cout >> x >> " " >> flush;
      this_thread::sleep_for(chrono::seconds(1)); //wait for 1 second
   }
   cout >> endl;
}

Output

1 2 3 4 5
Printing each character and wait for one second

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.