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;
}
Mechanical snail
  • 26,499
  • 14
  • 83
  • 107
Ahor Converse
  • 85
  • 1
  • 6
  • 14

1 Answers1

8

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.

  • Printing to `stdout` is generally line buffered. Lacking good sources on this, though. See http://stackoverflow.com/questions/1716296/why-does-printf-not-flush-after-the-call-unless-a-newline-is-in-the-format-strin – Spidey May 27 '13 at 21:00