I'd like to know how to check if a user types the "backspace" character.
I'm using the getch() function i.e. "key = getch()"
in my C program and i'd like to check when backspace is pressed. the line:
if(key = '\b') { ....
doesn't work.
\b by itself only moves the cursor. The usual way of erasing the last character on the console is to use the sequence "\b \b". This moves the cursor one space backwards, and prints a whitespace to erase the character, and backspaces again so that new output start at the old position.
In modern systems, the backspace key is often mapped to the delete character (0x7f in ASCII or Unicode), although the backspace key's function of deleting the character before the cursor remains. The backspace key is commonly used to go back a page or up one level in graphical web or file browsers.
Type the Alt code number 9224 and release the Alt key.
The problem with reading Backspace is that most terminals are 'cooked' in that keys like backspace are handled by the terminal driver. However, the curses function getch()
can read the backspace as it's not tied to the terminal.
I just noticed your code is using getch()
for input. I ran a little test program and getch()
returns 127 when you hit backspace. Therefore try:
if (key == 127 || key == 8) { ... /* Checks for both Delete or Backspace */
Also note that your sample code uses the assignment operator =
when it should be using the equality operator ==
The type of i/o stream may helps. Standard input stream is a kind of line buffered stream, which do not flush until you write a '\n' char into it. Full buffered stream never flush until the buffer is full. If you write a backspace in full buff stream, the '\b' may be captured.
Reference the unix environment advantage program.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With