Skip to content
Advertisement

How to stop backspace from appearing in nCurses using C?

I am currently writing an ncurses shell and in order to read input it is important to read it character by character and hence I am using the mvwgetch command. And incrementing a counter as it reads character by character. The problem is that whenever I press a an arrow key or a backspace their output is being printed. So, if for example I press backspace, ^? is being printed.

while ((command[i] = mvwgetch(promptwin, promptline, posx)) != 'n') {
    if (command[i] == 7) { // if entered character is a backspace
        i =-2;
        posx =- 2;
        mvwdelch(promptwin, promptline, posx);
        mvwdelch(promptwin, promptline, posx - 1);
        command[i] = '';
    } else {
        posx++;
        posyx[1] = posx;
        wmove(promptwin, promptline, posx);
    }
    i++;
}

It is required to read characters in order to keep track of where the cursor is found on the screen. In my code, there is my attempt at solving this problem but it still is displaying these characters. PS: working on linux.

Advertisement

Answer

SOLVED

Turns out the problem was that the code for backspace is 127. Therefore it was not being recognised. To handle backspaces it now executes the following code.

if(c == 127 || c == 8){                     //if character inserted is backspace or delete
                        if(posx != tcount) {
                            mvwprintw(promptwin, promptline, (posx + 1), " ");
                            mvwprintw(promptwin, promptline, posx, " ");
                            mvwprintw(promptwin, promptline, (posx - 1), " ");
                            wmove(promptwin, promptline, (posx - 2));
                            command[(chara - 1)] = '';
                            chara--;
                            posx--;
                            posyx[1] = posx;
                        } else {
                            mvwprintw(promptwin, promptline, (posx + 1), " ");
                            mvwprintw(promptwin, promptline, posx, " ");
                        }
                    } else {
                        command[chara] = c;
                        posx++;
                        posyx[1] = posx;
                        wmove(promptwin, promptline, posx);
                        chara++;
                    }
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement