First, a bit of revisionist history.
In the old days, when everybody used stdio.h
library to do I/O, text that was viewed interactively was typically line buffered (or even unbuffered), and text that was not was fully buffered. So, if you output '\n'
to the stream, it would "always" do the Right Thing: lines users were looking at get flushed and seen immediately, and lines getting dumped to file get buffered for maximum performance.
Unfortunately, it isn't actually always the Right Thing; the runtime cannot always predict how users actually want to view the output of your program. One common trap is redirecting STDOUT
-- people get used to running their program in a console and seeing the output (with its line-buffered behavior) in the console, and then for whatever reason (e.g. long running job) they decide to redirect STDOUT
to a file, and are promptly surprised by the fact the output is no longer line-buffered.
I have seen weeks of supercomputer time wasted for this reason; the output was infrequent enough that the buffering prevented anyone from being able to tell how the job was progressing.
C++'s iostream
library, however, was designed to make it easy to do the Right Thing here. Except when synchronizing with stdio
, it doesn't do this funny "maybe line-buffered maybe fully-buffered" thing. It always uses full buffering (except when you do unbuffered stuff, of course), and if you want things flushed on newline, you do so explicitly.
So if you're dumping a bunch of formatted text to a file that people won't be looking at until it's done, you write \n
for your line breaks.
But if you're writing text people might actually want to look at while you're writing it, you use std::endl
for your line breaks, and it gets displayed immediately. And if you're writing several lines at once, you can even do better: use '\n'
for the intermediate line breaks and std::endl
for the final one (or '\n'
and std::flush
). Although in this setting performance usually doesn't matter so it's usually fine to just use std::endl
for all of the line breaks.