-2

Following is my code : -

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

int main()
{
    int i;
    printf("Continue in...");
    for (i = 10; i > 0 ; --i)
    {
        printf("%d",i);
        sleep(1);
        printf("\b");
    }
}

I am trying to make a countdown timer in C, so that only the value of i changes on the STDOUT, and the words "Continue in..." stay as it is on the shell(i.e at the same location of screen).

But the code above produces nothing for 10 seconds, rather just prints the string "Continue in..." after 10th second.

I read this answer which says that the behaviour of \b is terminal dependent. My question is what should I edit in my code to make its output independent from the output device.

Community
  • 1
  • 1
Dipunj
  • 33
  • 1
  • 3
  • 12

3 Answers3

3

The output of the printf function is typically line buffered. That means you won't see any output until a newline is printed.

If you call fflush(stdout), that will flush the output buffer so you can see the results.

printf("Continue in...");
fflush(stdout);
for (i = 10; i > 0 ; --i)
{
    printf("%d",i);
    fflush(stdout);
    sleep(1);
    printf("\b");
    if  (i == 10) printf("\b  \b");   // for 10 you need to erase 2 characters
}
dbush
  • 205,898
  • 23
  • 218
  • 273
0

Alternately, call setvbuf(stdout, NULL, _IONBF, 0) at the start.

Mischa
  • 2,240
  • 20
  • 18
-1

You have to add \n in printf("%d",i); after %d . As buffer doesn't gets flushed with new line or until it is full.

LPs
  • 16,045
  • 8
  • 30
  • 61
user7345878
  • 492
  • 2
  • 7
  • 20