Possible Duplicate:
C++: “std::endl” vs “\n”
I'm wondering if there is any significant difference between these two ways to print newline :
cout << endl; //approach1
cout << "\n"; //approach2
Is there any practical difference?
Possible Duplicate:
C++: “std::endl” vs “\n”
I'm wondering if there is any significant difference between these two ways to print newline :
cout << endl; //approach1
cout << "\n"; //approach2
Is there any practical difference?
Yes, they're different.
"\n"
is just a string of length 1 that gets appended to stdout.
std::endl
, instead, is an object that will cause to append the newline character ("\n"
) AND to flush stdout buffer. For this reason it will take more processing.
endl
and not with "\n"
, and that's all there is to it as far as C++ is concerned. –
Meyerhof unitbuf
is set of course) endl
forces the flush, but just because you're using "\n"
instead of endl
doesn't mean you've avoided flushing the buffer. –
Candlewick operator<<
on it? (Note: When I say "underlying stream" I mean the particular instance of std::ostream
-- i.e. a filestream or stringstream. Perhaps I was not clear?) My point is that the stream is allowed to flush whenever it wants. You can force it to flush, but you cannot prevent it from flushing. In most common implementations, for the console streams, a newline just happens to trigger a flush -- the C++ standard doesn't say this has to happen, but it doesn't disallow it either. –
Candlewick operator<<
functions, which are defined in terms of the generic ostream
-- not the particular instance you're using. –
Candlewick © 2022 - 2024 — McMap. All rights reserved.
endl
will flush the stream. Unless you absolutely need to flush the stream you can use either of them. – Salaam