I have a doubt with the endl
stream handler function.
According to the book I'm reading (Deitel), it flushes endl
the output buffer.
What does this mean? Since if I put "\n"
or std::endl
at the end cout
I receive the same output.
Is there a way to be able to see the difference?
endl
is used to generate line break:the result will be:
note that for
hola3
yhola4
was not usedendl
endl
has the same result as \n, the only difference is that itstd::endl
flushes the output buffer, and '\n' does not, ie if you want to force an output. usesendl
the same example but with
\n
:What they say in the text you have read is correct and you can also read it in any documentation of
std::endl
:In Spanish:
Keep in mind that the operating system implements the data stream that outputs to the user's terminal in a different way than the output to a data stream to a file, a pipe to another application, etc.
So in a normal application with direct output to the terminal you wouldn't be able to tell the difference between flushing the data stream buffer and not flushing it.
To show you the difference I am going to use the following code:
By executing the code normally (
./pruebas
) we are sending the standard output to the user's terminal. There will be no difference between usingstd::endl
or not because the operating system will automatically flush the temporary memory ( buffer ) as soon as a carriage return (\n
) is encountered .When executing the application by sending its output to a pipeline to a second application (
./pruebas | more
) the operating system will not automatically flush the buffer on encountering the carriage return character , so during the first three print iterations nothing will appear on the screen because everything is stored in a temporary memory of the data stream that will not be sent tomore
be displayed on the user's terminal until the first is executedstd::endl
.You can see here the effect explained above:
What advantages or uses do they have
"\n"
andstd::endl
?Advantage of using
"\n"
:Advantages of using
std::endl
:When sending text to the user's terminal, it is convenient to make sure that the user reads the information that we have just presented. Although the operating system automatically flushes the buffer, this information may not be displayed to the user when using display enhancement tools such as
more
,less
,tail -f
,cat
, etc.In a communication through a TCP or UNIX connection, you make sure that the data flow has been sent (note, but that does not mean that it has been read by the other end).