Search code examples
cncurses

Using backspace with ncurses


I have a simple ncurses program set up that reads characters one at a time with getch() and copies them into a buffer. The issue I am having is detecting a press of the backspace key. Here is the relevant code:

while((buffer[i] = c = getch()) != EOF) {
    ++i;
    if (c == '\n') {
        break;
    }
    else if (c == KEY_BACKSPACE || c == KEY_DC || c == 127) {
        i--;
        delch();
        buffer[i] = 0;
    }
    refresh();
}

But when attempting to run this code, this is what appears on the screen after trying to delete characters from the line "this is a test":

this is a test^?^?^?

and the contents of buffer are:

this is a test

With gdb I know that the if statement checking for a delete/backspace is being called, so what else should I be doing so that I can delete characters?


Solution

  • It looks like ^? is what's echoed to the screen when you enter a DEL character.

    You could probably call delch() twice, but then you'd have to figure out which characters echo as two-character (or more) sequences.

    Your best bet is probably to call noecho() and explicitly print the characters yourself.