“\ n”或'\\\<br/>'或std :: endl to std :: cout? [英] "\n" or '\n' or std::endl to std::cout?
问题描述
这是多年以来,因为我停止使用 std :: endl
结束行写入 std :: cout
,然后开始使用\\\
。
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';
在此:
std::cout << variable << "\n";
推荐答案
其实,'\ n'
应该是默认值。除非你想显式地刷新流(你什么时候和为什么你想这样做),没有必要使用 std :: endl
。 sup> 1
当然,许多书和教程使用 std :: endl
作为默认值。这是不幸的,可能会导致严重的性能错误。
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 use std::endl
at all.1
Of course, many books and tutorials use std::endl
as the default. That is unfortunate and might lead to serious performance bugs.
我想使用'\\\
或使用
'\\ \\ n
,但是后者是一个(两个)字符的数组,必须逐个字符打印,为此必须设置循环,这比输出单个字符。当然,当做IO这很少是重要的,但如果有疑问,当你想输出一个字符文字,输出一个字符文字,而不是一个整个字符串文字。
一个很好的副作用所以你在你的代码中沟通,你希望只输出一个字符,而不是偶然地这样做。
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 请注意, std: :cout
默认绑定到 std :: cin
,这会导致 std :: cout
在任何输入操作之前被刷新,以便在用户输入某些内容之前打印任何提示。
1 Note that std::cout
is tied to std::cin
by default, which leads to std::cout
being flushed before any input operation, so that any prompt will be printed before the user has to input something.
这篇关于“\ n”或'\\\<br/>'或std :: endl to std :: cout?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!