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?
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.
There's actually a simpler way of doing it by using the forms library alongside ncurses. If you change your code to this:
while((buffer[i] = c = getch()) != EOF) {
++i;
if (c == '\n') {
break;
}
else if (c == KEY_BACKSPACE || c == KEY_DC || c == 127) {
form_driver(Form, REQ_DEL_PREV);
}
refresh();
}
It will backspace without a problem. You can find some (Albeit limited) documentation for the REQ_DEL_PREV command here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With