I am trying to understand buffer, endl vs \n and why the latter is more efficient than endl.
Specifically, I am reading this https://www.geeksforgeeks.org/buffer-flush-means-c/
The following code is supposedly output 1,2,3,4,5 at once
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
for (int i = 1; i <= 5; ++i)
{
cout << i << " " ;
Sleep(300);
}
cout << endl;
return 0;
}
whereas the following will output each integer one at a time:
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
for (int i = 1; i <= 5; ++i)
{
cout << i << " " << flush;
Sleep(300);
}
return 0;
}
However, both looks exactly the same during the time of execution, they appear one a time. Is my understanding wrong?
I'm also confused why endl is less efficient compared to \n.
From what I read, endl adds a \n and then flushes.
Isn't this more efficient, since it waits for the buffer to be full then output everything at once, compared to \n?
Please correct my flawed understanding, thank you.