Search code examples
cerror-handlingkeypress

How do I properly do key trapping in C?


I've been trying to figure out how to prevent an unwanted input from appearing when a user is inputting. My code is a bit weird because when the user is presses backspace the characters are still on the screen when they should be deleted.

#include<stdio.h>
#include<conio.h>
#include<ctype.h>
    int main(void)
    {
        char ch;
        while(1){
           ch=getch();
           if(isalpha(ch)){
              putchar(ch);
           }
           else if(ch=='\b'){
              putchar('\b');
           }
           else if(ch=='\n'||ch==EOF)
              break;
        }
        return 0;
    }

Solution

  • try this

    else if(ch=='\b'){
       putchar('\b');
       putchar(' ');
       putchar('\b');
    }