Linux 中 std::cout 的奇怪行为
我正在尝试使用 std::cout
在 2 个嵌套的 for
循环中打印结果。但是,结果不会立即打印到控制台,而是延迟打印(在 for 循环或程序完成之后)。
我认为这种行为不正常,在 Windows 下打印工作正常。该程序不使用线程。
问题可能出在哪里? (Ubuntu 10.10 + NetBeans 6.9)。
I am trying to print results in 2 nested for
cycles using std::cout
. 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. The program does not use threads.
Where could be the problem? (Ubuntu 10.10 + NetBeans 6.9).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
std::cout
是一个流,并且被缓冲。您可以通过多种方式冲洗它:johny:
如果在循环之前刷新缓冲区,则不会影响循环中的输出。您必须在循环中或循环后进行冲洗才能看到输出。
std::cout
is an stream, and it is buffered. You can flush it by several ways:johny:
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.
如果您不刷新输出,则不能保证您的输出在程序外部可见。它没有在终端中打印的事实只是 linux 中当输出是 tty 时进行行缓冲的默认行为的结果。如果你在 Linux 上运行你的程序,并将其输出通过管道传输到另一个东西,比如
那么默认缓冲区将大得多,很可能至少为 4096 字节。因此,在大缓冲区填满之前,不会显示任何内容。但实际上,该行为是特定于操作系统的,除非您自己刷新 std::cout 。
要刷新 std::cout,请使用 :
也,使用
是快捷方式
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. If you run your program on linux with its output piped to another thing, like
Then the default buffer will be MUCH larger, most likely it will be at least 4096 bytes. So nothing will get displayed until the big buffer gets full. but really, the behaviour is OS specific unless you flush std::cout yourself.
To flush std::cout, use :
also, using
is a shortcut to