C++ "\n" 或 '\n' 或 std::endl 到 std::cout?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8311058/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
"\n" or '\n' or std::endl to std::cout?
提问by Some programmer dude
It was many years now since I stopped using std::endl
to end lines when writing to std::cout
, and started using "\n"
instead.
自从我std::endl
在写入 时停止使用结束行std::cout
并开始使用它已经很多年了"\n"
。
But now I start seeing more snippets of code using '\n'
instead, and I started wonder what might be best.
但现在我开始看到更多的代码片段被使用'\n'
,我开始想知道什么可能是最好的。
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.
当我问这个问题时,我似乎认为换行符'\n'
刷新了缓冲区。现在我知道这取决于。
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.
默认情况下std::cin
绑定到旧的 Cstdin
FILE*
流,并std::cout
绑定到stdout
. 换行符的刷新来自这种绑定。默认情况下stdout
,如果连接到终端,则是行缓冲的。这意味着新行将刷新其缓冲区。因此,当使用 打印换行符时std::cout
,这将导致stdout
被刷新。
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.
如果stdout
未连接到的终端(例如,输出已经被重定向或用管道输送),或者如果之间的联系std::cout
和stdout
被打破,然后换行不会冲洗任何东西。
回答by sbi
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'
应该是默认的。除非您还想显式刷新流(以及何时以及为什么要这样做?),否则根本不需要使用std::endl
。1
当然,很多书籍和教程std::endl
都是默认使用的。这是不幸的,可能会导致严重的性能错误。
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 intendedto output only a single character, and not just accidentally did this.
我想 using'\n'
或 using之间几乎没有区别"\n"
,但后者是一个(两个)字符的数组,必须逐个字符地打印,必须为其设置一个循环,这比输出单个字符更复杂. 当然,在执行 IO 时这很少重要,但如果有疑问,当您想输出一个字符文字时,输出一个字符文字,而不是整个字符串文字。
这样做的一个很好的副作用是你在代码中传达了你打算只输出一个字符,而不是偶然地这样做。
1Note 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.
1请注意,默认std::cout
绑定到std::cin
,这会导致std::cout
在任何输入操作之前被刷新,以便在用户必须输入内容之前打印任何提示。
回答by B?ови?
There are no the best. You use what you need :
没有最好的。你使用你需要的东西:
- '\n' - to end the line
- "some string\n" - the end the line after some string
std::endl
- to end the line and flush the stream
- '\n' - 结束行
- "some string\n" - 某个字符串后的行尾
std::endl
- 结束行并刷新流
回答by jalf
They do different things. "\n"
Outputs a newline (in the appropriate platform-specific representation, so it generates a "\r\n"
on Windows), but std::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 use std::endl
.
他们做不同的事情。"\n"
输出一个换行符(以适当的特定于平台的表示形式,因此它"\r\n"
在 Windows 上生成 a ),但std::endl
执行相同操作并刷新流。通常,您不需要立即刷新流,它只会降低您的性能,因此在大多数情况下没有理由使用std::endl
.
回答by Chris Parton
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 :)
编辑:我的回答措辞不佳,这可能让人们相信我认为“\n”实际上打印了一个空字符。这当然是错误的:)
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.
编辑 2:查看 C++ 引用后,char
无论如何 s 都是通过引用传递的,因此那里没有区别。唯一的区别是必须在 cstring 中搜索定界字符。由于这个事实,以下内容不正确。
'\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 a char*
to operator<<()
(usually 4 bytes on a 32-bit system) as opposed to a single byte for a char
.
'\n'
会比 稍微高效一点"\n"
,因为后者在末尾还包含一个空字符,这意味着您要发送一个char*
to operator<<()
(在 32 位系统上通常为 4 个字节),而不是一个char
.
In practice, this is borderline irrelevant. Personally, I follow the convention that Vladimir outlined.*
在实践中,这与边界无关。就我个人而言,我遵循弗拉基米尔概述的惯例。*
回答by zangw
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'; // output newline std::cout.flush(); // then flush
std::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::cout << variable << std::endl;
std::endl
输出换行符,但它也会刷新输出流。换句话说,效果与std::cout << variable << '\n'; // output newline std::cout.flush(); // then flush
std::cout << variable << '\n';
'\n'
输出一个换行符 achar,
因此ostream& operator<< (ostream& os, char c);
将被使用。std::cout << variable << "\n";
"\n"
是 aconst char[2]
,所以ostream& operator<< (ostream& os, const char* s);
会被使用。我们可以想象,这个函数将包含一个循环,我们可能会争辩说仅仅打印一个换行符是多余的。
回答by zangw
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 use std::endl
instead of writing '\n'
to the stream (whether as an isolated character or part of a string).
std::endl
冲洗流。当您希望发生这种情况时——例如,因为您希望您的输出及时对用户可见——您应该使用std::endl
而不是写入'\n'
流(无论是作为独立字符还是字符串的一部分)。
Sometimes, you can get away without explicitly flushing the stream yourself; e.g. in a linux environment, if cout
is synchronized with STDOUT
(this is the default) and is writing to a terminal, then by default, the stream will be line bufferedand will automatically flush every time you write a new line.
有时,您无需自己明确刷新流就可以逃脱;例如,在 linux 环境中,如果cout
与STDOUT
(这是默认值)同步并正在写入终端,那么默认情况下,流将被行缓冲,并且每次写入新行时都会自动刷新。
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 bufferedinstead.
但是,依赖这种行为是有风险的。例如,在相同的 linux 环境中,如果您决定stdout
在重定向到文件或通过管道传输到另一个进程的情况下运行程序,那么默认情况下,流将被块缓冲。
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.
类似地,如果您稍后决定关闭与 stdio 的同步(例如为了效率),那么实现将倾向于使用iostream
的缓冲机制,它没有行缓冲模式。
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 use std::flush
or std::ostream::flush
, but I usually find std::endl
more convenient), or do something else that ensures flushing happens often enough, such as configuring stdout
to be line buffered (assuming that's adequate).
由于这个错误,我看到了很多浪费的生产力;如果输出在写入时应该是可见的,那么您应该std::endl
显式使用(或使用std::flush
or std::ostream::flush
,但我通常觉得std::endl
更方便),或者做一些其他事情来确保刷新经常发生,例如配置stdout
为行缓冲(假设这是足够的)。