Ahor Converse
Ahor Converse

Reputation: 113

Why is my nanosleep not working...?

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

Upvotes: 0

Views: 1534

Answers (1)

user2404501
user2404501

Reputation:

Your code is calling printf at the correct intervals, but stdout is holding all the output in its buffer until the end.

Put an fflush(stdout); before the nanosleep to force it to print immediately.

Upvotes: 8

Related Questions