简体   繁体   English

Linux中std :: cout的奇怪行为

[英]Strange behaviour of std::cout in Linux

I am trying to print results in 2 nested for cycles using std::cout . 我正在尝试使用std::cout在2个嵌套for周期中打印结果。 However, the results are not printed to the console immediately, but with delay (after both for cycles or the program have been finished). 但是,结果不会立即打印到控制台,而是会延迟(在两个周期或程序都完成之后)。

I do not consider such behavior normal, under Windows printing works OK. 我认为这种行为不正常,在Windows下可以正常打印。 The program does not use threads. 该程序不使用线程。

Where could be the problem? 问题可能出在哪里? (Ubuntu 10.10 + NetBeans 6.9). (Ubuntu 10.10 + NetBeans 6.9)。

std::cout is an stream, and it is buffered. std::cout是一个流,并且已缓冲。 You can flush it by several ways: 您可以通过几种方法冲洗它:

std::cout.flush();

std::cout << std::flush;

std::cout << std::endl;  // same as:  std::cout << "\n" << std::flush`


johny: 约翰尼:

I am flushing the buffer before the cycle using std::endl. 我在循环之前使用std :: endl刷新缓冲区。 The problem arises when printing dot representing % of processed data inside the cycle. 当打印代表周期内已处理数据百分比的点时,会出现问题。

If you flush the buffer before the cycle, that does not affect the output in the cycle. 如果循环之前刷新缓冲区,不影响循环的输出。 You have to flush in or after the cycle, to see the output. 您必须在循环中或循环后冲洗,才能看到输出。

If you don't flush your output, your output is not guaranteed to be visible outside your program. 如果不刷新输出,则不能保证您的输出在程序外部不可见。 The fact that it is not printing in your terminal is just a consequence of the default behavior in linux to do line buffering when the output is a tty. 它不在您的终端中打印的事实仅仅是由于Linux在输出为tty时默认行行缓冲的结果。 If you run your program on linux with its output piped to another thing, like 如果您在Linux上运行程序,其输出通过管道传递到另一件事,例如

 ./your_program | cat

Then the default buffer will be MUCH larger, most likely it will be at least 4096 bytes. 然后,默认缓冲区将大很多,最有可能的是至少为4096个字节。 So nothing will get displayed until the big buffer gets full. 因此,直到大缓冲区填满之前,什么都不会显示。 but really, the behaviour is OS specific unless you flush std::cout yourself. 但是实际上,除非您自己刷新std :: cout,否则行为是特定于操作系统的。

To flush std::cout, use : 要刷新std :: cout,请使用:

std::cout << std::flush;

also, using 另外,使用

std::cout << std::endl;

is a shortcut to 是通往的捷径

std::cout << '\n' << std::flush;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM