Home > other >  How do I "fflush" backspace character by character in C?
How do I "fflush" backspace character by character in C?

Time:10-30

I know what fflush does and it works well in the following code

#include <stdio.h>
#include <unistd.h>
int main()
{
    printf("%s", "Hello");
    fflush(stdout);
    usleep(1000000);
    printf("%s", ", ");
    fflush(stdout);
    usleep(1000000);
    printf("%s", "world!");
    fflush(stdout);
    usleep(1000000);
    printf("\n");
    return 0;
}

where I'm trying to make my program look like some kind of animation.

However, when I tried to make the deletion look like animation, shown below

#include <stdio.h>
#include <unistd.h>
int main()
{
  printf("%s", "Hello, world!");
  usleep(1000000);
  printf("\b");
  fflush(stdout);
  usleep(1000000);
  printf("\b");
  fflush(stdout);
  return 0;
}

printf("\b"); and fflush cannot backspace the characters one by one, how do I fix the issue?

CodePudding user response:

"Backspace" is rather badly named, it doesn't actually print a "space" of any kind. What it typically does it just move the cursor one step back on the line.

If you want to overwrite the previous character with a space, then you need to print a space as well (and another backspace to put the cursor in the correct position):

printf("\b \b");
  •  Tags:  
  • c
  • Related