Home > Blockchain >  How to check if character read in through read system call is a backspace?
How to check if character read in through read system call is a backspace?

Time:09-27

I have the following piece of code which reads in a character using the read system write call:

char character;
read(STDIN_FILENO, &character, 1);

How do I detect whether character is a backspace or not? Based on that, I need to delete the last character from the console output.

CodePudding user response:

You can check if it's a backspace by looking for character number 8 (ASCII). It's written in C as '\b'.

However did you forget to put your terminal in RAW mode?

To change terminal to raw mode, see this answer to a different question: https://stackoverflow.com/a/13129698/14768 ; the code you want is in function changemode.

CodePudding user response:

#include<iostream>
#include<string>
#include<cstdlib>
#include <windows.h> 
#include <winuser.h> 
using namespace std;

int main(){
    
    string str;
    getline(cin, str);
    
    if(GetAsyncKeyState(8)) //checks to see if the input contained any backspaces
    {
        cout<<"Backspace was detected"; 
    }
    else{
        cout<<"Backspace Not detected";
    }
    
    return 0;
}

or similarly using a character:

#include<iostream>
#include<string>
#include<cstdlib>
#include <windows.h> 
#include <winuser.h> 
using namespace std;

int main(){
    
    char c;
    cin.get(c);
    
    if(GetAsyncKeyState(8)) //checks to see if the input contained any backspaces
    {
        cout<<"Backspace was detected"; 
    }
    else{
        cout<<"Backspace Not detected";
    }
    
    return 0;
}

I now realised you are using C instead of C so all you do is change the libraries you are using.

  •  Tags:  
  • c
  • Related