[英]Cout in While loop Strange behaviour
My code look like below 我的代码如下所示
int i=0;
while(i<10){
cout<<"Hello";
sleep(1);
i++
}
In Windows the code prints on each loop but in Linux it prints everything after exiting while loop . 在Windows中,代码在每个循环上打印,但是在Linux中,它在退出while循环后打印所有内容。 And also if I put an endl at the last of cout then it prints on each loop.
而且,如果我将endl放在cout的最后,那么它将在每个循环上打印。 Why this happening ?.
为什么会这样? Can anyone explain this behavior?.
谁能解释这种行为?
Try to use cout.flush()
; 尝试使用
cout.flush()
; maybe the two OS has different policy in term of buffering the stdout. 也许两个操作系统在缓冲标准输出方面有不同的策略。
For efficiency reasons, sometimes the standard streams will be implemented with a buffer. 出于效率原因,有时标准流将使用缓冲区来实现。 Making lots of tiny writes can be slow, so it will store up your writes until it gets a certain amount of data before writing it all out at once.
进行大量次要写入可能很慢,因此它将存储您的写入,直到获得一定数量的数据,然后立即全部写入。
Endl forces it to write out the current buffer, so you'll see the output immediately. Endl强制它写出当前缓冲区,因此您将立即看到输出。
#include <iostream>
using namespace std;
int main()
{
int i = 0;
while(i < 10){
cout << "Hello" << endl;
sleep(1);
++i;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.