1

How can I generate a "readable" backspace in command prompt?

I have a tiny C app and I'm trying to read a backspace from input with getchar() method.

Is there any key combination to trigger this (and still being able to capture it)? (Similar to Ctrl-Z to trigger an EOF)

Alex
  • 5,510
  • 8
  • 35
  • 54

3 Answers3

1

Backspace is special! Normally you will need to use some raw/unbuffered keyboard I/O mode to capture it.

On Windows you may want to try using getch instead of getchar. See also: What is the difference between getch() and getchar()?

Community
  • 1
  • 1
Jack Whitham
  • 609
  • 4
  • 9
1

You can use curses function getch() to read backspace.
Chech the following link - how to check for the "backspace" character in C

In the above link in answer ascii value of backspace is used to read it .

Community
  • 1
  • 1
ameyCU
  • 16,489
  • 2
  • 26
  • 41
  • Well, `getch` is deprecated to the point it does not allow to use it and "forces" you to use `_getch` instead – Alex Jul 08 '15 at 09:16
1

Ascii code of backspace button is 127, so every function returns an integer from terminal input will probably return 127 in case of backspace. Be careful because it is the same code for delete button.

Linux

See this answer first and implement your own getch() then follow Windows code example (obviously without conio.h lib).

Windows

Just add #include<conio.h>in the beginning of your source file.

This is my SSCCE, just need to write something like this

int main(void) {
    int c;
    while (1) {
        c = getch();
        if (c == 127) {
            printf("you hit backspace \n");
        } else {
            printf("you hit the other key\n");
        }
    }
    return 0;
}
Community
  • 1
  • 1
dagi12
  • 449
  • 1
  • 5
  • 20
  • 1.To be able to run your code I had to change `getch()` to `_getch()` 2.Also it's funny that in order to get a 127 value I had to press CTRL and BACKSPACE (so single BACKSPACE is not doing the trick) – Alex Jul 08 '15 at 09:14