What does buffer flush means in C++ ?

C++Server Side ProgrammingProgramming

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
raja
Updated on 30-Jul-2019 22:30:26

Advertisements