Invisible Hippo
Invisible Hippo

Reputation: 124

sleep() executes all at once rather then when it is called

I tried to make a simple quiz in Linux like so:

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

void main()
{   
    printf("Simple arithmetic\n");
    printf("5 * 7 + 4 / 2 = ?\n");
    sleep(3);                       //wait for 3 seconds
    printf("And the answer is");
    for(int i = 5; i > 0; i--){ //wait for another 5 seconds printing a '.' each second
        sleep(1);
        printf(" .");
    }
    printf("\n%d!\n", 5*7+4/2);     //reveal the answer
}

Problem is, this outputs the frist two printf's and then waits for 8 or so seconds, and then prints everything else out like this:

>> Simple arithmetic
>> 5 * 7 + 4 / 2 = ?
>> // waits for 8 seconds instead of 3
>> And the answer is.....
>> 37! // prints everything out with no delay in-between

Why does this happen and what can I do to fix it? Thanks for the help!

Upvotes: 0

Views: 70

Answers (1)

rajesh6115
rajesh6115

Reputation: 735

flush is required if you want immediate output.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void main()
{   
        printf("Simple arithmetic\n");
        printf("5 * 7 + 4 / 2 = ?\n");
        sleep(3);                       //wait for 3 seconds
        printf("And the answer is");
        for(int i = 5; i > 0; i--){  //wait for another 5 seconds printing a '.' each second
                sleep(1);
                printf(" .");
                fflush(stdout); // this line will do magic
        }
        printf("\n%d!\n", 5*7+4/2);     //reveal the answer
}

Upvotes: 2

Related Questions