C++ 强制 std::cout 刷新(打印到屏幕)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22026751/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:54:02  来源:igfitidea点击:

c++ force std::cout flush (print to screen)

c++coutflush

提问by synaptik

I have code such as the following:

我有如下代码:

std::cout << "Beginning computations..."; // output 1
computations();
std::cout << " done!\n";                  // output 2

The problem, however, is that often output #1 and output #2 appear (virtually) simultaneously. That is, often output #1 does not get printed to the screen until after computations()returns. Since the entire purpose of output #1 is to indicate that something is going on in the background (and thus to encourage patience from the user), this problem is not good.

然而,问题是输出#1 和输出#2 经常(几乎)同时出现。也就是说,在computations()返回之前,输出 #1 通常不会打印到屏幕上。由于输出 #1 的全部目的是表明后台正在发生某些事情(从而鼓励用户的耐心),因此这个问题并不好。

Is there any way to force the std::coutbuffer to get printed before the computations()call? Alternatively, is there some other way (using something other than std::cout) to print to standard out that would fix this problem?

有什么方法可以强制std::coutcomputations()调用之前打印缓冲区?或者,是否有其他方法(使用 以外的其他方法std::cout)打印到标准输出可以解决此问题?

回答by Joseph Mansfield

Just insert std::flush:

只需插入std::flush

std::cout << "Beginning computations..." << std::flush;

Also note that inserting std::endlwill also flush after writing a newline.

另请注意,std::endl在写入换行符后插入也会刷新。

回答by user1810087

In addition to Joseph Mansfield answer, std::endldoes the flush too (besides a new line).

除了 Joseph Mansfield 的回答之外,std::endl也进行了冲洗(除了换行)。

Inserts a endline character into the output sequence os and flushes it as if by calling os.put(os.widen('\n')) followed by os.flush().

将结束符插入到输出序列 os 中并刷新它,就像调用 os.put(os.widen('\n')) 后跟 os.flush() 一样。