为什么要使用endl,当我可以使用换行符? [英] Why use endl when I can use a newline character?

查看:194
本文介绍了为什么要使用endl,当我可以使用换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我可以使用 \\时,有理由使用 endl with cout \\ n ?我的C ++书说使用endl,但我不明白为什么。是 \\\
不支持像 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?

推荐答案

endl appends '\\\
'
到流 在流上调用 flush()

endl appends '\n' to the stream and calls flush() on the stream. So

cout << x << endl;

相当于

cout << x << '\n';
cout.flush();

流可以使用内部缓冲区,当流刷新时,在 cout 的情况下,您可能不会注意到差异,因为它与 cin 绑定 c>,但对于任意流,例如文件流,您会注意到多线程程序中的差异。

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) with cin, 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,当我可以使用换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆