什么时候必须刷新C ++中的输出流? [英] When must the output stream in C++ be flushed?

查看:136
本文介绍了什么时候必须刷新C ++中的输出流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我理解 cout<<与 cout<<相比, preferredn endl; cout<< ‘n’不会刷新输出流。

I understand cout << '\n' is preferred over cout << endl; but cout << '\n' doesn't flush the output stream. When should the output stream be flushed and when is it an issue?

究竟是什么刷新?

推荐答案


何时必须刷新C ++中的输出流?

When must the output stream in C++ be flushed?

何时您要确保写入其中的数据对于其他程序或(对于文件流而言)对读取同一文件的其他流可见(与该文件无关);

When you want to be sure that data written to it is visible to other programs or (in the case of file streams) to other streams reading the same file which aren't tied to this one; and when you want to be certain that the output is written even if the program terminates abnormally.

因此,当您在进行冗长的计算之前打印一条消息时,会希望这样做,或打印一条消息以表明出了点问题(尽管您通常会使用 cerr 为此,在每次输出后会自动刷新)。

So you would want to do this when printing a message before a lengthy computation, or for printing a message to indicate that something's wrong (although you'd usually use cerr for that, which is automatically flushed after each output).

通常不需要刷新 cerr (默认情况下,其 unitbuf 标记设置为在每次输出后刷新),或在从 cin 读取之前刷新 cout (这些流被绑定在一起,以便 cout 在读取 cin 之前会自动刷新。

There's usually no need to flush cerr (which, by default, has its unitbuf flag set to flush after each output), or to flush cout before reading from cin (these streams are tied so that cout is flushed automatically before reading cin).

如果您的程序的目的是产生大量输出,无论是输出到 cout 还是文件,请不要在每行之后刷新-这可能会大大降低输出速度。

If the purpose of your program is to produce large amounts of output, either to cout or to a file, then don't flush after each line - that could slow it down significantly.


什么是冲洗?

What exactly is flushing?

输出流包含内存缓冲区,通常比基础输出要快得多。输出操作将数据放入缓冲区;冲洗将其发送到最终输出。

Output streams contain memory buffers, which are typically much faster to write to than the underlying output. Output operations put data into the buffer; flushing sends it to the final output.

这篇关于什么时候必须刷新C ++中的输出流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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