maobe
maobe

Reputation: 77

C ncurses KEY_BACKSPACE not working

Im trying to work this code using the the nurses library. I'm trying to make it print the letter i whenever I press the backspace key, but it doesn't seem to be working. It seem pretty simple. It should be working but it isn't. am I missing something? Thanks in advance

#include <ncurses.h>
#include <stdio.h>

int main () {

  short ch;
  initscr();
  keypad(stdscr, TRUE);
  clear();
  noecho();
  ch = getch();

  while(ch != '\n') {
    if(ch == KEY_BACKSPACE) {
      mvaddch(90, 90, 'i');
    }
    ch = getch();
  }

  endwin();
}

Upvotes: 6

Views: 6004

Answers (3)

Kamal Barshevich
Kamal Barshevich

Reputation: 81

Actually, getch() returns int, but not short or char. Try using int instead of char, as KEY_BACKSPACE consists of more then 1 byte.

Also, why not, consider using wgetch(window) instead of getch():

int ch;
ch = wgetch(<here put your window handler>)

Also use int or uint32_t for ch instead of short int in this case, as BACKSPACE key code (KEY_BACKSPACE) returned by wgetch() also can use up to 4 bytes.

Upvotes: 0

ManuelAtWork
ManuelAtWork

Reputation: 2458

A robust keyboard handler for NCurses catches at least three potential values:

short ch = getch();
...
switch (ch) {
...
case KEY_BACKSPACE:
case 127:
case '\b':
  /* Handle backspace here. */
  break;
...
}

The reason is that the backspace key can lead to different return values. It depends on the platform, the terminal and the current settings.

Upvotes: 7

Nietzsche
Nietzsche

Reputation: 48

I had some problems like you and did a little program to output the code of a key combination, thus temporarly fixing the problem.

#include <stdio.h>
#include <ncurses.h>
#include <locale.h>
#include <wchar.h>

int main()
{
    setlocale(LC_CTYPE, ""); initscr(); raw(); noecho(); keypad(stdscr, TRUE);
    wint_t c;
    get_wch(&c);
    endwin();
    printf("Keycode: %d\n", c);
    return 0;
}

It outputs 127 for backspace on my computer. I'd just add a #define ALT_BACKSPACE 127 somewhere in my program and I'm read to go.

Upvotes: 1

Related Questions