0

std::endl vs \n

Are any particular one which should be used at specific times? I understand endl flushes the stream (although i'm not 100% what this means) while \n is simply a newline.

3
Contributors
2
Replies
25
Views
2 Years
Discussion Span
Last Post by rubberman
1

Are any particular one which should be used at specific times?

I favor the guideline that you should use '\n' unless you know that the stream must be flushed immediately and nothing else consistently does it for you. Times where you have a lone output statement and the stream must be flushed with std::endl or std::flush are surprisingly rare, mostly due to tied streams:

cout << "Prompt: "; // No consistent flushing here
cin >> choice; // This statement flushes cout for you

I understand endl flushes the stream (although i'm not 100% what this means)

When an output stream is flushed, the internal buffer is sent to the destination device. For performance reasons, when you write characters to a stream they're collected into a buffer. Then when the buffer fills up, it's written in toto to the target device. The performance benefit is that a potentially expensive operation is minimized by reducing the number of times it happens.

0

A newline in a string is just some more data to send, whereas std::endl will send a newline and then flush the output. You can also use std::flush to flush the output in those cases where you don't want a newline (input prompts for example). IE: cout << "Enter code:" << std::flush;

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.