Delete only user input, not the entire screen

Viewed 64

Is there any way to remove only the user input and not the entire program? Here's the program

#include <stdio.h>

int main() {
    int a;
    printf("text");
    scanf("%d", &a);
}

If I were to do clrscr() it would remove everything, and that's not what I want.

1 Answers

There are 2 possible approaches to your problem:

  • you can try and prevent user input from echoing to the terminal. This requires changing the configuration of the terminal using system specific calls such as tcgetattr() and tcsetattr(), it is very tricky and error prone.

  • you can try and erase the user input after it has been validated using ANSI escape sequences to move the cursor up and kill the end of line. This is much simpler but not fool proof and of course it does not prevent privy eyes from looking at the screen while the user types the sensitive data.

Here is an example:

#include <stdio.h>

char *get_string(const char *prompt, char *dest, size_t size) {
    printf("\r%s: \033[K", prompt);
    if (!fgets(dest, size, stdin)))
        return NULL;
    // assuming the cursor is on the next line, move it
    // to the beginning of the line, then up one line, show the prompt again
    // erase the end of the line and skip to the next line
    printf("\r\033[A%s: \033[K\n", prompt);
    return dest;
}
Related