当我可以使用换行符时为什么要使用 endl ?
当我只能使用 \n
时,是否有理由将 endl
与 cout
一起使用?我的 C++ 书上说要使用 endl,但我不明白为什么。 \n
是否不像 endl
那样受到广泛支持,或者我遗漏了什么?
Is there a reason to use endl
with cout
when I can just use \n
? My C++ book says to use endl, but I don't see why. Is \n
not supported as widely as endl
, or am I missing something?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
endl
将'\n'
附加到流并调用flush()
溪流。因此相当于
流可以使用内部缓冲区,当流被刷新时,该缓冲区实际上会被流式传输。对于
cout
,您可能不会注意到差异,因为它以某种方式与cin
同步(捆绑),但对于任意流,例如文件例如,您会注意到多线程程序中的差异。这里有一个关于为什么需要冲洗的有趣讨论。
endl
appends'\n'
to the stream and callsflush()
on the stream. Sois equivalent to
A stream may use an internal buffer which gets actually streamed when the stream is flushed. In case of
cout
you may not notice the difference since it's somehow synchronized (tied) withcin
, but for an arbitrary stream, such as file stream, you'll notice a difference in a multithreaded program, for example.Here's an interesting discussion on why flushing may be necessary.
endl
不仅仅是\n
字符的别名。当您向cout
(或任何其他输出流)发送内容时,它不会立即处理和输出数据。例如:在上面的示例中,函数调用有可能在输出刷新之前开始执行。使用endl可以强制在执行第二条指令之前进行刷新。您还可以使用
ostream::flush
函数。endl
is more than just an alias for the\n
character. When you send something tocout
(or any other output stream), it does not process and output the data immediately. For example:In the above example, there's is some chance that the function call will start to execute before the output is flushed. Using
endl
you force the flush to take place before the second instruction is executed. You can also ensure that with theostream::flush
function.