为什么我的纳米睡眠不起作用......?

Aho*_*rse 0 c sleep stdout stream

我编写了以下代码来逐字符地打印段落,间隔为0.3秒.但是当我编译并运行它时,它会打印出句子中的所有内容.为什么纳秒功能不起作用?

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

int main() {
    int i = 0;
    struct timespec t1, t2;
    t1.tv_sec = 0;
    t1.tv_nsec = 300000000L;

    char story[] = {"I want to print this story / letter by letter on the screen./"};
    while(story[i] != '\0') {
        if(story[i] == '/')
            sleep(1);
        else
            printf("%c", story[i]);
    nanosleep(&t1, &t2);
        i++;
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

小智 8

您的代码printf以正确的间隔进行调用,但是stdout将所有输出保留在其缓冲区中直到结束.

fflush(stdout);在nanosleep之前放一个强制它立即打印.