lundi 19 avril 2021

trying to understand the effect of flushing a buffer problem

I'm a complete beginner in C++, so I'm deeply sorry if my question would sound stupid or something.

I have been reading a book that gave a simple intro about stream buffers, and in some cases it's important to flush the buffer, so to understand the effect I ran the following code:

code1:

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

code2:

#include <iostream>
#include <thread>
#include <chrono>
using namespace std;

int main()
{
   for (int i = 1; i <= 5; ++i)
   {
      cout << i << " " << flush;
      this_thread::sleep_for(chrono::seconds(1));
   }
   return 0;
}

Both codes give the same output, there is no difference at all, they print 1 sleeping for 1 second followed by 2, sleep for another second, and so on.

I have tried to run the codes in both DevC++ and CodeBlocks, which gave the same result.

The book says the result of code1 --> "the program waits for 5 seconds and prints all the numbers at once", and the result of code2 --> "the program prints the number waits for 1 second and prints the second number and so on".

I really don't understand what went wrong.

Aucun commentaire:

Enregistrer un commentaire