"std::endl" vs "\n"
The varying line-ending characters don't matter, assuming the file is open in text mode, which is what you get unless you ask for binary. The compiled program will write out the correct thing for the system compiled for.
The only difference is that std::endl
flushes the output buffer, and '\n'
doesn't. If you don't want the buffer flushed frequently, use '\n'
. If you do (for example, if you want to get all the output, and the program is unstable), use std::endl
.
The difference can be illustrated by the following:
std::cout << std::endl;
is equivalent to
std::cout << '\n' << std::flush;
So,
- Use
std::endl
If you want to force an immediate flush to the output. - Use
\n
if you are worried about performance (which is probably not the case if you are using the<<
operator).
I use \n
on most lines.
Then use std::endl
at the end of a paragraph (but that is just a habit and not usually necessary).
Contrary to other claims, the \n
character is mapped to the correct platform end of line sequence only if the stream is going to a file (std::cin
and std::cout
being special but still files (or file-like)).
There might be performance issues, std::endl
forces a flush of the output stream.