0

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!

Invisible Hippo
  • 124
  • 1
  • 1
  • 9
  • Have a look at http://stackoverflow.com/questions/1716296/why-does-printf-not-flush-after-the-call-unless-a-newline-is-in-the-format-strin – nnn Mar 16 '17 at 00:45
  • `wait` undeclared. `i > wait;` --> `i > 0;` – BLUEPIXY Mar 16 '17 at 00:46

1 Answers1

2

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
}
rajesh6115
  • 705
  • 9
  • 21