简体   繁体   English

C ++控制台输出问题

[英]Issue with C++ console output

#include <iostream>                                                             

using namespace std;

int main()
{
   cout << 1;
   while (true);
   return 0;
}

I thought that this program should print 1 and then hung. 我以为这个程序应该打印1然后挂起。 But it doesn't print anything, it just hungs. 但它没有打印任何东西,只是挂了。 cout << endl or cout.flush() can solve this problem, but I still want to know why it's not working as expected :) This problem appeared during codeforces contest and I spent a lot of time on looking at strange behavior of my program. cout << endlcout.flush()可以解决这个问题,但我还是想知道为什么它如预期不工作:)这个问题的过程中出现codeforces比赛和我花了很多时间在看我的节目的奇怪行为。 It was incorrect, it also hunged, hidden output was actually debug information. 它是不正确的,它也很浑浊,隐藏的输出实际上是调试信息。

I tried using printf (compiling with gcc) and it behaves as well as cout , so this question can be referred to C also. 我尝试使用printf (使用gcc编译),它的行为和cout一样好,所以这个问题也可以引用到C.

You writing to a buffer. 你写入缓冲区。 You need to flush the buffer. 您需要刷新缓冲区。 As @Guvante mentioned, use cout.flush() or fflush(stdout) for printf. 正如@Guvante所提到的,对printf使用cout.flush()fflush(stdout)

Update: 更新:

Looks like fflush actually works with cout. 看起来fflush实际上适用于cout。 But don't do that - it may not be the fact in all cases. 但是不要这样做 - 在所有情况下都可能不是这样。

That is because cout buffers output. 那是因为cout缓冲输出。 You have to flush the buffer for it to actually print. 您必须刷新缓冲区才能实际打印。

endl and flush() both perform this flushing. endlflush()都执行此刷新。

Also note that your program hangs because you have an infinite loop ( while(true); ). 还要注意你的程序挂起,因为你有一个无限循环( while(true); )。

The reason it does this is so that if you are printing a lot of data (say 1000 numbers) it can do so drastically more efficiently. 这样做的原因是,如果您要打印大量数据(比如1000个数字),它可以大大提高效率。 Additionally most minor data points end with endl anyway, since you want your output to span multiple lines. 此外,大多数次要数据点都以endl结尾,因为您希望输出跨越多行。

Concerning printf , the same as cout holds: you're printing into a buffer, you need to flush it with fflush(stdout); 关于printf ,和cout一样:你要打印到缓冲区,你需要用fflush(stdout);刷新它fflush(stdout); . Termination will flush the buffer, this is why you can see the output without your infinite loop. 终止将刷新缓冲区,这就是为什么你可以在没有无限循环的情况下看到输出。

See Why does printf not flush after the call unless a newline is in the format string? 请参阅为什么printf在调用后不会刷新,除非换行符在格式字符串中? for more information. 欲获得更多信息。

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

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