usleep()函数不允许循环继续

ggg*_*ggg 2 c++ sleep

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(void)
{
        int i=0;
        while(i<10)
        {
                printf("%d", i);
                usleep(10000); // or sleep(1)
                i++;
        }
        return 0;
}
Run Code Online (Sandbox Code Playgroud)

我希望程序持续10秒,即打印1 - 等待1秒 - 打印2 - 等待1秒,依此类推,直到结束.但它没有这样做 - 它只是等待所有的时间(10秒),然后打印整个数字阵列,没有任何时间延迟,它只是立即打印0123456789.编辑:我尝试使用sleep()而不是usleep,但它是一样的如何解决它?为什么会这样?

Art*_*ius 13

您的输出缓冲区未被刷新.默认情况下,当流中出现新行时会写入输出.把你printf改成这个:

printf("%d\n", i);
Run Code Online (Sandbox Code Playgroud)

或试试这个:

printf("%d", i);
fflush(stdout);
Run Code Online (Sandbox Code Playgroud)

此外,如果要删除行缓冲行为,可以使用setvbuf()_IONBUF模式.


小智 5

旁边 - 要通过1秒usleep,请致电usleep(1000000)