I understand that questions like, difference between endl
and \n
have been answered many times on SO. But they only mention that endl
is able to flush the buffer onto the stdout
, while \n
, does not.
So, what I understand by buffer being flushed is that, the input given is stored in a buffer, and is passed onto the stdout
only when it comes across endl
, or some explict flush
functions. If so, I expected that the following code :
#include <iostream>
#include <unistd.h>
int main(void)
{
std::cout << "Hello\nworld";
sleep(2);
std::cout << std::endl;
return 0;
}
To display:
After 2 seconds
Hello
World
But the actual output was:
Hello
After 2 seconds
World
Why is it so ?
shouldn't \n
also be stored in the buffer and only when endl
is encountered buffer is to be flushed/displayed onto the stdout
, but from what I observe \n
is acting the same way as endl
.
Converting comments into an answer.
It depends on where cout
is going. If it goes to a terminal ('interactive device'), then it can't be fully buffered — it is usually line buffered, meaning that characters appear after a newline is printed, or could in theory be unbuffered. If it is going to a pipe or file or other non-interactive destination, the endl
forces the data out even if the stream is fully buffered, as it usually will be.
I also wanted to know if I provided neither new line character nor
endl
, will the output be displayed on thestdout
once it reaches the end of the program, I know it does for terminal, but is it applicable to all types ofstdout
?
Yes, when the file stream is closed at the (normal) end of the program, pending output will be flushed. It'll also be flushed when the buffer is full. If the program aborts, pending output usually won't be flushed.