4

I'm a newbie to programming, I started teaching myself yesterday, I've been getting everything but I honestly, do not understand the difference between

std::cout << x;

and

std::cout << x << std::endl;

Nobody has explained this to me, and I'm asking to stay on the safe side.

Paul Beckingham
  • 14,495
  • 5
  • 33
  • 67
ssleepie
  • 73
  • 6

2 Answers2

12

endl writes a new-line to the stream, so subsequent output will appear on the next line. It also flushes the stream's buffer, usually causing a slow-down.

This flushing means that 99% of the time, endl is a mistake, and you should just write "\n" (or '\n') instead. When you really do want to flush the stream, I think it's better to make that explicit by invoking std::flush instead:

std::cout << x << '\n' << std::flush;

As far as run-time actions goes, this is equivalent to using std::endl, but in terms of making your intent clear, it's drastically superior.

Community
  • 1
  • 1
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • 5
    Just an observation that might help some readers: if you want to output some manner of prompt, such as `std::cout << "type your name:";`, you don't (by default) need to use `endl` or `flush` before attempting input from `std::cin`, as they're "tied" streams and take care of that automatically. – Tony Delroy Mar 25 '16 at 00:51
0

The std::endl adds a newline code to a stream and also flushes the output buffer and std::cout << x is just printing x. So if you got a code

cout << 5;
cout << 5;

it will be

55

as an output, but if you add a endl to a first cout the output will be

5

5

What i really recommend you is to use '\n' it is much more better than endl.

  • "i really recommend you is to use '\n' it is much more better than endl" Better for what? Performance? And what else? – KABoissonneault Mar 25 '16 at 02:09
  • It's good when I get it for free. If it can introduce other problems, I'd rather avoid it. Though to be honest, I'm personally using a wrapper around `printf` for logging instead of streams – KABoissonneault Mar 25 '16 at 12:51