我想在NCurses中使用 getstr()阅读使用输入。但是,当我使用箭头键时,它会打印键码而不是实际移动光标。如何让它向左移动以便我可以在文本传递到缓冲区之前编辑它?
答案 0 :(得分:3)
Curses不会解释箭头键的输入。您唯一得到的是KEY_LEFT在设置键盘模式时用作退格键。但幸运的是,写下你自己的替代品并不太复杂。以下适用于我:
#include <ctype.h>
#include <string.h>
#include <ncurses.h>
static void
readline(char *buffer, int buflen)
/* Read up to buflen-1 characters into `buffer`.
* A terminating '\0' character is added after the input. */
{
int old_curs = curs_set(1);
int pos = 0;
int len = 0;
int x, y;
getyx(stdscr, y, x);
for (;;) {
int c;
buffer[len] = ' ';
mvaddnstr(y, x, buffer, len+1);
move(y, x+pos);
c = getch();
if (c == KEY_ENTER || c == '\n' || c == '\r') {
break;
} else if (isprint(c)) {
if (pos < buflen-1) {
memmove(buffer+pos+1, buffer+pos, len-pos);
buffer[pos++] = c;
len += 1;
} else {
beep();
}
} else if (c == KEY_LEFT) {
if (pos > 0) pos -= 1; else beep();
} else if (c == KEY_RIGHT) {
if (pos < len) pos += 1; else beep();
} else if (c == KEY_BACKSPACE) {
if (pos > 0) {
memmove(buffer+pos-1, buffer+pos, len-pos);
pos -= 1;
len -= 1;
} else {
beep();
}
} else if (c == KEY_DC) {
if (pos < len) {
memmove(buffer+pos, buffer+pos+1, len-pos-1);
len -= 1;
} else {
beep();
}
} else {
beep();
}
}
buffer[len] = '\0';
if (old_curs != ERR) curs_set(old_curs);
}
为了使其正常工作,您需要启用键盘移动和cbreak模式,并关闭回声模式:
cbreak();
noecho();
keypad(stdscr, TRUE);
我希望这有帮助,
约亨