0

段落を 0.3 秒間隔で 1 文字ずつ出力する次のコードを作成しました。しかし、コンパイルして実行すると、すべてが文章で出力されます。ナノ秒関数が機能しないのはなぜですか?

#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の前に anfflush(stdout);を付けて、強制的にすぐに印刷させます。

于 2013-05-27T20:43:17.297 に答える