需求为能够直接获取键盘时间,对待输入不需要点击回车就能够直接相应。
类似于使用键盘进行拳皇等小游戏时的操作,可以直接在终端输入键盘指令就能够得到响应。
通常我们使用的终端输入方式cin需要点击回车后才能完成本次输入。因此cin并不能满足本次的要求
在Linux下可以通过termio进行键盘时间的获取,并且屏蔽掉回车键。如果需要查询某一个键的key数值,可以直接按键尝试,但遗憾的是不支持上下左右键。

#include <termio.h>
#include <stdio.h>
#include <unistd.h>
int scanKeyboard()
{
// struct termios
// {
// tcflag_t c_iflag; /* input mode flags */
// tcflag_t c_oflag; /* output mode flags */
// tcflag_t c_cflag; /* control mode flags */
// tcflag_t c_lflag; /* local mode flags */
// cc_t c_line; /* line discipline */
// cc_t c_cc[NCCS]; /* control characters */
// speed_t c_ispeed; /* input speed */
// speed_t c_ospeed; /* output speed */
// #define _HAVE_STRUCT_TERMIOS_C_ISPEED 1
// #define _HAVE_STRUCT_TERMIOS_C_OSPEED 1
// };
int in;
struct termios new_settings;
struct termios stored_settings;
tcgetattr(STDIN_FILENO,&stored_settings); //获得stdin 输入
new_settings = stored_settings; //
new_settings.c_lflag &= (~ICANON); //
new_settings.c_cc[VTIME] = 0;
tcgetattr(STDIN_FILENO,&stored_settings); //获得stdin 输入
new_settings.c_cc[VMIN] = 1;
tcsetattr(STDIN_FILENO,TCSANOW,&new_settings); //
in = getchar();
tcsetattr(STDIN_FILENO,TCSANOW,&stored_settings);
return in;
}
int main(int argc, char *argv[]) {
while(1){
printf(":%d\r\n",scanKeyboard());
// int input_id = scanKeyboard();
// switch(input_id) {
// case 119: //w or can set as case 'w':
// case 87: //W case 'W':
// break;
// case 115: //s
// case 83: //S
// break;
// case 97: //a
// case 67: //A
// break;
// case 100: //d
// case 68: //D
// break;
// default:
// break;
// }
}
}
参考:
https://www.runoob.com/w3cnote/c-get-keycode.html
https://blog.youkuaiyun.com/u013467442/article/details/51173441
3220





