Many C++ books contain example code like this...
std::cout << \"Test line\" << std::endl;
...so I\'ve always done that too. But
The std::endl
manipulator is equivalent to '\n'
. But std::endl
always flushes the stream.
std::cout << "Test line" << std::endl; // with flush
std::cout << "Test line\n"; // no flush
There's another function call implied in there if you're going to use std::endl
a) std::cout << "Hello\n";
b) std::cout << "Hello" << std::endl;
a) calls operator <<
once.
b) calls operator <<
twice.
They will both write the appropriate end-of-line character(s). In addition to that endl will cause the buffer to be committed. You usually don't want to use endl when doing file I/O because the unnecessary commits can impact performance.
If you use Qt and endl
, you could accidentally end up using an incorrect endl
which gives you very surprising results. See the following code snippet:
#include <iostream>
#include <QtCore/QtCore>
#include <QtGui/QtGui>
// notice that there is no "using namespace std;"
int main(int argc, char** argv)
{
QApplication qapp(argc,argv);
QMainWindow mw;
mw.show();
std::cout << "Finished Execution!" << endl;
// This prints something similar to: "Finished Execution!67006AB4"
return qapp.exec();
}
Note that I wrote endl
instead of std::endl
(which would have been correct) and apparently there is a endl
function defined in qtextstream.h (which is part of QtCore).
Using "\n"
instead of endl
completely sidesteps any potential namespace issues.
This is also a good example why putting symbols into the global namespace (like Qt does by default) is a bad idea.
There might be performance issues, std::endl
forces a flush of the output stream.
The varying line-ending characters don't matter, assuming the file is open in text mode, which is what you get unless you ask for binary. The compiled program will write out the correct thing for the system compiled for.
The only difference is that std::endl flushes the output buffer, and '\n'
doesn't. If you don't want the buffer flushed frequently, use '\n'
. If you do (for example, if you want to get all the output, and the program is unstable), use std::endl
.