0

I have written the following code to print the paragraph character by character with an interval of 0.3 seconds. But when I compile and runs it, it prints everything in sentence. Why is the nanosecond function not working?

#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;
}
4

1 回答 1

8

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

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

于 2013-05-27T20:43:17.297 回答