【发布时间】:2013-05-22 05:02:31
【问题描述】:
我正在用 c/c++ 实现一个密钥阅读器程序。我正在使用Linux。我知道无缓冲的 getchar 函数将返回很少的键数据值。对于所有 ASCII 键(a-z、A-Z、1-9、标点符号、回车、制表符和 ESC),getchar() 将返回一个值。对于其他键,例如方向键,会有ESC键读取,但是当再次调用getchar()时,它会得到另一个值(A、B、C或D)。
A = 65
B = 66
向上箭头 = 27 91 65
F5 = 27 91 49 53 126
ESC = 27
满桌here
有什么方法可以检查是否有更多的字符要读取,或者是否只有一个字符?当一个键被读取并且它的第一个值是 ESC 我不知道它是一个以 ESC 开头的功能键还是只是 ESC 键。
#include <stdlib.h>
#include <stdio.h>
#include <sys/ioctl.h>
#include <iostream>
#include <string>
#include <termios.h>
#include <unistd.h>
using namespace std;
int main(int argc, char *argv[]) {
int ch[5];
int i;
struct termios term;
tcgetattr( STDIN_FILENO, &term );
term.c_lflag &= ~( ICANON | ECHO );
tcsetattr( STDIN_FILENO, TCSANOW, &term );
ch[0] = getchar();
// If ch[0] = 27 and there is more data in the buffer
// printf("You pressed a function key");
// Else
// printf("You pressed ESC");
return 0;
}
【问题讨论】:
-
你的目标是什么操作系统?
-
尝试在 stdin 上使用 read 并将 stdin 的属性设置为非阻塞。读取直到返回大小为 0。
-
如果您输入的键超出了 ASCII 字符集中所包含的内容(例如功能键或带有另一个键的控制键),则返回值通常是没有意义的。这些键在 ANSI C 定义之外,因此 getchar() 在处理这些键和/或键组合时的行为取决于系统。
-
@paddy 我正在使用 linux。
-
您会考虑使用ncurses 作为您的输入吗?我很确定它会为你处理所有的 ANSI 代码。