“\n”或'\n'或 std::endl 到 std::cout?
自从我在写入 std::cout
时停止使用 std::endl
结束行,并开始使用 "\n" 代替。
但现在我开始看到更多使用 '\n'
的代码片段,我开始想知道什么可能是最好的。
除了明显的一个是字符串,另一个是字符之外,使用这个还有什么优点:
std::cout << variable << '\n';
超过这个:
std::cout << variable << "\n";
后期添加:
当我问这个问题时,我似乎认为换行符 '\n'
刷新缓冲区。现在我知道这取决于。
默认情况下,std::cin
绑定到旧的 C stdin
FILE*
流,以及 std::cout
与 stdout
绑定。换行符的刷新来自于这种绑定。默认情况下,如果连接到终端,stdout 是行缓冲的。这意味着新行将刷新其缓冲区。因此,当使用 std::cout 打印换行符时,将导致 stdout 被刷新。
如果 stdout
未连接到终端(例如输出已重定向或通过管道传输),或者如果 std::cout
和 stdout< 之间存在联系/code> 被破坏,那么换行符将不会刷新任何内容。
It was many years now since I stopped using std::endl
to end lines when writing to std::cout
, and started using "\n"
instead.
But now I start seeing more snippets of code using '\n'
instead, and I started wonder what might be best.
Besides the obvious that one is a string, and the other a character, is there any advantage to using this:
std::cout << variable << '\n';
Over this:
std::cout << variable << "\n";
Late addition:
When I asked this question I seemed to think that newline '\n'
flushed the buffer. Now I know that it depends.
By default std::cin
is tied to the old C stdin
FILE*
stream, and std::cout
is tied to stdout
. The flushing on newline comes from this tying. By default stdout
, if connected to a terminal, is line-buffered. That means a new line will flush its buffers. So when printing a newline using std::cout
, that will lead to stdout
being flushed.
If stdout
is not connected to a terminal (for example the output has been redirected or is piped), or if the tie between std::cout
and stdout
is broken, then newlines will not flush anything.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
实际上,
'\n'
应该是默认值。除非您还想显式刷新流(以及何时以及为什么要这样做?),否则根本不需要使用std::endl
。1当然,许多书籍和教程都使用 std::endl 作为默认值。不幸的是,这可能会导致严重的性能错误。
我想使用
'\n'
或使用"\n"
之间没有什么区别,但后者是一个(两个)字符的数组,必须打印字符按字符,需要设置循环,这比输出单个字符更复杂。当然,在进行 IO 时,这并不重要,但如果有疑问,当您想要输出一个字符文字时,请输出一个字符文字,而不是整个字符串文字。这样做的一个很好的副作用是,您可以在代码中传达您打算仅输出单个字符,而不仅仅是意外地这样做。
1 请注意,默认情况下,
std::cout
与std::cin
绑定,这会导致std::cout
在任何输入操作之前被刷新,以便在用户必须输入内容之前打印任何提示。Actually,
'\n'
should be the default. Unless you want to also explicitly flush the stream (and when and why would you want to do that?), there is no need to usestd::endl
at all.1Of course, many books and tutorials use
std::endl
as the default. That is unfortunate and might lead to serious performance bugs.I suppose there's little difference between using
'\n'
or using"\n"
, but the latter is an array of (two) characters, which has to be printed character by character, for which a loop has to be set up, which is more complex than outputting a single character. Of course, when doing IO this rarely matters, but if in doubt, when you want to output one character literal, output a character literal, rather than a whole string literal.A nice side-effect of doing so is that you communicate in your code that you intended to output only a single character, and not just accidentally did this.
1 Note that
std::cout
is tied tostd::cin
by default, which leads tostd::cout
being flushed before any input operation, so that any prompt will be printed before the user has to input something.没有最好的。您使用您需要的内容:
std::endl
- 结束行并刷新流There are no the best. You use what you need :
std::endl
- to end the line and flush the stream他们做不同的事情。
"\n"
输出换行符(以适当的平台特定表示形式,因此它在 Windows 上生成"\r\n"
),但std: :endl
执行相同的操作并刷新流。通常,您不需要立即刷新流,这只会降低性能,因此在大多数情况下没有理由使用std::endl
。They do different things.
"\n"
Outputs a newline (in the appropriate platform-specific representation, so it generates a"\r\n"
on Windows), butstd::endl
does the same and flushes the stream. Usually, you don't need to flush the stream immediately and it'll just cost you performance, so for the most part there's no reason to usestd::endl
.编辑:我的答案措辞很糟糕,这可能会让人们相信我认为“\n”实际上打印了一个空字符。这当然是错误的:)
编辑 2:查看了 C++ 参考后,
char
无论如何都是通过引用传递的,因此没有区别。唯一的区别是必须在 cstring 中搜索分隔字符。 由于这个事实,下面的内容是不正确的。'\n'
会比"\n"
更高效,因为后者末尾还包含一个空字符,这意味着您要向operator<<()
发送一个char*
(在 32 位上通常为 4 个字节)系统)而不是单个字节字符
。实际上,这是无关紧要的。就我个人而言,我遵循弗拉基米尔概述的惯例。*
Edit: I worded my answer poorly, which may have lead people to believe that I thought "\n" actually printed a null character. This is of course wrong :)
Edit 2: Having looked at a C++ reference,
char
s are passed by reference anyway, so there's no difference there. The only difference is that the cstring will have to be searched for a delimiting character. The below isn't correct due to this fact.'\n'
would be ever so slightly more efficient than"\n"
, because the latter also contains a null character on the end, which means you're sending achar*
tooperator<<()
(usually 4 bytes on a 32-bit system) as opposed to a single byte for achar
.In practice, this is borderline irrelevant. Personally, I follow the convention that Vladimir outlined.*
std::cout <<变量<< std::endl;
std::endl
输出换行符,但它也会刷新输出流。换句话说,效果与相同
std::cout << 效果相同变量<< '\n';
'\n'
为char 输出换行符,
因此ostream&运算符<< (ostream& os, char c);
将被使用。std::cout <<变量<< “\n”;
"\n"
是一个const char[2]
,因此ostream&运算符<< (ostream&os, const char* s); 将被使用。我们可以想象,这个函数将包含一个循环,我们可能会认为仅仅打印出换行符是多余的。
std::cout << variable << std::endl;
std::endl
output a newline, but it also flushes the output stream. In other words, same effect asstd::cout << variable << '\n';
'\n'
output a newline for achar,
henceostream& operator<< (ostream& os, char c);
will be used.std::cout << variable << "\n";
"\n"
is aconst char[2]
, soostream& operator<< (ostream& os, const char* s);
will be used. We can imagine, this function will contain a loop, we might argue is overkill to just print out a newline.std::endl
刷新流。当您希望发生这种情况时 - 例如,因为您希望用户及时看到输出 - 您应该使用std::endl
而不是编写'\ n'
到流(无论是作为独立字符还是字符串的一部分)。有时,您无需自己显式刷新流即可逃脱;例如,在 Linux 环境中,如果
cout
与STDOUT
同步(这是默认设置)并且正在写入终端,则默认情况下,流将为 行缓冲并且每次写入新行时都会自动刷新。然而,依赖这种行为是有风险的。例如,在同一个 Linux 环境中,如果您决定运行程序时将
stdout
重定向到文件或通过管道传输到另一个进程,则默认情况下,流将是块缓冲的 相反。同样,如果您稍后决定关闭与 stdio 的同步(例如为了提高效率),那么实现将倾向于使用 iostream 的缓冲机制,该机制没有行缓冲模式。
我见过很多由于这个错误而造成的生产力浪费;如果输出在写入时应该可见,那么您应该显式使用
std::endl
(或使用std::flush
或std::ostream: :flush
,但我通常发现std::endl
更方便),或者做一些其他事情来确保刷新经常发生,例如将stdout
配置为行缓冲(假设是 足够的)。std::endl
flushes the stream. When this something you want to happen -- e.g. because you expect your output to be made visible to the user in a timely fashion -- you should usestd::endl
instead of writing'\n'
to the stream (whether as an isolated character or part of a string).Sometimes, you can get away without explicitly flushing the stream yourself; e.g. in a linux environment, if
cout
is synchronized withSTDOUT
(this is the default) and is writing to a terminal, then by default, the stream will be line buffered and will automatically flush every time you write a new line.However, it is risky to rely on this behavior. e.g. in the same linux environment, if you decide to run your program with
stdout
being redirected to a file or piped to another process, then by default, the stream will be block buffered instead.Similarly, if you later decide to turn off synchronization with stdio (e.g. for efficiency), then implementations will tend to use
iostream
's buffering mechanisms, which doesn't have a line buffering mode.I have seen much wasted productivity due to this mistake; if output should be visible when it is written, then you should either use
std::endl
explicitly (or usestd::flush
orstd::ostream::flush
, but I usually findstd::endl
more convenient), or do something else that ensures flushing happens often enough, such as configuringstdout
to be line buffered (assuming that's adequate).