mikejosnton
mikejosnton

Reputation: 15

How to make countdown timer print result on single line in C?

I have code here which works as a countdown timer but it prints results on a new line like this:

10
9
8
7
6
5
4
3
2
1

here is my code:

int timer()
{
        int count;
        count = 10;

        while(count != 0)
        {
                printf("Time: \t%d \n", count);
                count--;
                sleep(1);
        }

        printf("\nCount down timer has expired\n");
        return 0;
}

what I've tried so far is to change \n to \r to print on a single line but it did not work. I'm trying to make it clear the line and print the next number in the line then clear that and print the next one if that makes sense

Upvotes: 0

Views: 1046

Answers (3)

Alex
Alex

Reputation: 61

Try to add fflush(stdout) after using \r in your printf as mentioned by pmg:

int timer()
{
        int count;
        count = 10;

        while(count != 0)
        {
                printf("Time: \t%d \r", count);
                fflush(stdout);
                count--;
                sleep(1);
        }

        printf("\nCount down timer has expired\n");
        return 0;
}

Upvotes: 0

pmg
pmg

Reputation: 108938

Use "\b \b" to clear one character. Imagine you just printed "42": the 1st '\b' moves the cursor back to over the 2, then the space 'clears' that 2, and finally go back again one more space.

    printf("Time: \t");
    while(count != 0)
    {
            printf("%d", count);
            fflush(stdout);
            sleep(1);
            if (count >= 100) printf("\b \b");
            if (count >= 10) printf("\b \b");
            if (count >= 1) printf("\b \b");
            count--;
    }
    printf(" \n");

Upvotes: 0

Talha Quddoos
Talha Quddoos

Reputation: 556

Try changing printf("Time: \t%d \n", count); to printf("Time: \t%d \t", count);

Upvotes: 1

Related Questions