Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check for the "backspace" character in C

Tags:

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.

like image 620
joel Avatar asked Dec 06 '10 04:12

joel


People also ask

What is backspace character in C?

\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.

Is there a backspace character?

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.

How do you type the backspace symbol?

Type the Alt code number 9224 and release the Alt key.


2 Answers

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.

Edit

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 ==

like image 66
SiegeX Avatar answered Nov 03 '22 23:11

SiegeX


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.

like image 32
user531771 Avatar answered Nov 03 '22 23:11

user531771