5

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();
}
1
  • 3
    Remember that the terminal is by defaut in cooked mode, and you need either cbreak or raw mode to get certain keys, just turning off echoing is not enough. Also note that your code will write the character at the same position all the time, so you won't really know if you get multiple backspace key events. Nov 29, 2014 at 9:04

3 Answers 3

5

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.

1

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.

1
  • I was debugging a python curses application, so I had to remember to compile with -lncursesw
    – zje
    Mar 26, 2018 at 15:18
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.