waivek
waivek

Reputation: 193

No output when trying to make a countdown timer in c

I'm trying to make a rudimentary countdown timer with the following code

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

int main(int argc, char *argv[])
{
    printf("Enter time in minutes:");
    int x = 0;
    scanf("%d", &x);
    x = x*60;
    while(x!=0) {
        printf("Remaining time is %d\r", x);
        x--;
        sleep(1);
    }
    return 0;
}

However, when I run the code for x = 1, I get no immediate output. Is there anyway to fix this?

Upvotes: 0

Views: 578

Answers (1)

Yu Hao
Yu Hao

Reputation: 122403

Standard output is line buffered by default. If it's

printf("Remaining time is %d\n", x);

Note the \n here, it would output every time a \n is seen.

However, in your case, you use the carriage return \r on purpose. The alternative method is to flush the standard out manually like this:

printf("Remaining time is %d\r", x);
fflush(stdout);

Upvotes: 3

Related Questions