@gcampton:
Here is your definitive answer.
The difference between '\n' and endl is that endl is equal to '\n' PLUS a flush of the stream buffer. Internally, the ostreams have a buffer in which they "cache" the data, rather than writing the data through to the destination.
This cache is flushed to the destination at four times:
1. Upon explicit flush of the stream;
2. Upon explicit use of endl;
3. When the buffer is full;
4. When the stream is closed.
As a nicety, any time you use cin, the cout (and cerr, I think) streams is/are flushed. This allows code like this
to work:
1 2
|
cout << "Please enter a number (1-100): ";
cin >> number;
|
as otherwise, it is very possible the program will wait for the user to enter a number, but the prompt won't be displayed (until sometime after the user enters the number, whenever the stream is flushed) because it will be cached in the stream object.
So the bottom line is that you need either to use endl or flush if you want the user to see what you've output right away, otherwise there are no guarantees. So in your "simple" example above, be wary that as written, nothing guarantees that the user will see any of your output. Your "complex" example is fine.
Perhaps this leads to the following convention: when outputting a block of data, with potentially multiple cout or cerr statements consecutively, '\n' should be used for embedded newlines, but either endl (if a newline is desired) or flush (if a newline is not desired) should be used at the very end of the block.