I've just stepped into the world of competitive programming and therefore, was reading few articles to grasp the best strategies a programmer should follow while writing code in c++.
I read somewhere that one should use '\n'
in lieu of std::endl
at the end of the line because std::endl
forces the buffer to flush.
I didn't know what 'flushing of buffer' meant so I started searching for it and came across this answer What does flushing the buffer mean? After reading the answer the idea that I got 'flushing the buffer' was to print & wipe out everything in the output buffer to the console.
So, to check the validity of the answer I made this program on my machine.
#include <iostream>
#include <time.h>
using namespace std;
int main()
{
struct timespec tim, tim2;
tim.tv_sec = 3;
tim.tv_nsec = 0;
for(int i=0; i<5; i++)
{
cout << i << endl;
nanosleep(&tim , &tim2);
}
return 0;
}
The results I got on executing the program came as expected. The loop printed 0 to 4 with a delay of 3 seconds after each iteration.
However, when I changed endl
to '\n'
I was expecting the results to show on the console all at once after 15 seconds. But, the digits got outputted after the same delay it got outputted in the previous case. Now, if '\n'
doesn't flush the output buffer, shouldn't I've got the results as I was expecting?