Found an error in the tutorials

I probably am sure, but the lines in the tutorial:

cout << "Hello World!";

is not the right one! Feel free to lol me if you want because I'm probably not the first one to notice this. the correct way to code the line is this:

cout << "Hello World!" << endl;

Yes, I do hope that I am not the first one; the guy who wrote the tutorials please fix this!
Here's your "lol". There's nothing wrong with the hello world example and endl has no business being in it as it's just one line being output to the console.
It is perfectly correct...You don't need the std::endl.
Typically I use endl in place of ' \n ' when I have long complex cout statements, otherwise just ' ; ' or
' "..blah..blah...\n"; '
I have asked my lecturer about this a few times and each time she gives different made up reasoning, which is why I implement my own standards.

simple:
1
2
    cout << "Hello World this is:  \n" << program name;


complex;
1
2
    cout << "Hello World is the sum of: " << str1.length() << " and includes "
        << someRandomVariables << " and additionally " << anArrayElement[6] << endl;
ok never mind...

my first time in here and it was a bit complicated

lock please.
Topics don't get locked here :P
They get archived automatically (I think) after a month and then they are locked.
@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.

Last edited on
Topic archived. No new replies allowed.