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.
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.
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.
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;
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.