2

所以,我有下面的程序。它的作用是打印随机数,同时在控制台上将它们格式化为 10 的宽度。

现在,当我添加 sleep 函数时,我希望它每 10 毫秒(或更多)打印一个数字,但它所做的是,它每 100*10 毫秒打印 100 个输出。我想知道,为什么会发生这种情况?输出是缓冲还是什么?

#include <unistd.h>
#include <iostream>
#include <cstdlib>
#include <time.h>
#include <iomanip>

int main()
{
    srand(time(0));
    for (int i = 1; i < 1000000; i++)
    {
        usleep(10*1000);    // No matter the input, the same thing happens
        cout << setw(10) << rand()%(90*i) + 10*i;
    }
}

我在windows和unix上都试过了,完全一样。

4

1 回答 1

0

是的,输出确实被缓冲了。

用于std::cout.flush();手动冲洗。

请注意,std::endl(追加一个新行并)进行刷新。

于 2014-02-21T13:00:57.510 回答