开发者

how to check for the "backspace" character in C

开发者 https://www.devze.com 2023-01-28 07:41 出处:网络
I\'d like to know how to check if a user types the开发者_如何学Python \"backspace\" character. I\'m using the getch() function i.e. \"key = getch()\" in my C program and i\'d like to check when backs

I'd like to know how to check if a user types the开发者_如何学Python "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.


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


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.


You didn't say which library the getch() function comes from (it isn't part of the C standard), but if it's the one from ncurses you can check the value of key against KEY_BACKSPACE.


Try this:

#include <stdio.h>      /* printf   */
#include <ctype.h>      /* isalpha isdigit isspace etc      */

#define FALSE 0
#define TRUE  1

/* function declarations */
int char_type(char);

main()
{
 char ch;

 ch = 127;
 char_type(ch);

 ch = '\b';
 char_type(ch);

 return 0;
}

int char_type(char ch)
{
 if ( iscntrl(ch) != FALSE)
   printf("%c is a control character\n", ch); 
}

This is a complete program but it only tests for control characters. You could use principles of it, your choice. Just learning too!

See : http://www.tutorialspoint.com/c_standard_library/ctype_h.htm or lookup the functions for the ctype.h header file of the C Standard Library.

It's good that you're getting input. Thanks all for the info. I was just looking up backspace code and found this question.

BTW try '\0' before any char. Not sure what that does but it stops all code after it. Is that like the return 0; line?


I believe the system input driver is line buffered. So its not possible in standard C.

0

精彩评论

暂无评论...
验证码 换一张
取 消