C++: “std::endl” vs “\n”

2018-12-31 00:53发布

Many C++ books contain example code like this...

std::cout << "Test line" << std::endl;

...so I've always done that too. But I've seen a lot of code from working developers like this instead:

std::cout << "Test line\n";

Is there a technical reason to prefer one over the other, or is it just a matter of coding style?

12条回答
素衣白纱
2楼-- · 2018-12-31 01:31

If you didn't notice, endl is like pressing the ENTER KEY while "\n" is like pressing ENTER KEY + SPACE BAR.

查看更多
皆成旧梦
3楼-- · 2018-12-31 01:40

If you intend to run your program on anything else than your own laptop, never ever use the endl statement. Especially if you are writing a lot of short lines or as I have often seen single characters to a file. The use of endl is know to kill networked file systems like NFS.

查看更多
弹指情弦暗扣
4楼-- · 2018-12-31 01:42

There might be performance issues, std::endl forces a flush of the output stream.

查看更多
不再属于我。
5楼-- · 2018-12-31 01:43

The difference can be illustrated by the following:

std::cout << std::endl;

is equivalent to

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

So,

  • Use std::endl If you want to force an immediate flush to the output.
  • Use \n if you are worried about performance (which is probably not the case if you are using the << operator).

I use \n on most lines.
Then use std::endl at the end of a paragraph (but that is just a habit and not usually necessary).

Contrary to other claims, the \n character is mapped to the correct platform end of line sequence only if the stream is going to a file (std::cin and std::cout being special but still files (or file-like)).

查看更多
看淡一切
6楼-- · 2018-12-31 01:44

I've always had a habit of just using std::endl because it is easy for me to see.

查看更多
泛滥B
7楼-- · 2018-12-31 01:46

If you use Qt and endl, you could accidentally use the wrong endl, happened to me today and i was like ..WTF ??

#include <iostream>
#include <QtCore/QtCore> 
#include <QtGui/QtGui>
//notice that i dont have a "using namespace std;"
int main(int argc, char** argv)
{
    QApplication qapp(argc,argv);
    QMainWindow mw;
    mw.show();
    std::cout << "Finished Execution !" << endl << "...";
    // Line above printed: "Finished Execution !67006AB4..."
    return qapp.exec();
}

Of course that was my mistake, since i should have written std::endl, but if you use endl, qt and using namespace std; it depends on the order of the include files if the correct endl will be used.*

Of course you could recompile Qt to use a namespace, so you get a compilation error for the example above.

EDIT: Forgot to mention, Qt's endl is declared in "qtextstream.h" which is part of QtCore

*EDIT2: C++ will pick the correct endl if you have a using for std::cout or the namespace std, since std::endl is in the same namespace as std::cout, C++'s ADL mechanism will pick std::endl.

查看更多
登录 后发表回答