在很多情况下,我们希望在控制台下,按键盘字符,程序马上反应而不是等待回车后才响应。
在Windows平台下可以使用getch ()(要求#include “conio.h“)实现,而在Linux平台下没有这个头文件,也就无法使用这个函数。 车到山前必有路,我们另有办法。 先看下面这段代码: struct termios stored_settings; struct termios new_settings; tcgetattr (0, &stored_settings); new_settings = stored_settings; new_settings.c_lflag &= (~ICANON); new_settings.c_cc[VTIME] = 0; new_settings.c_cc[VMIN] = 1; tcsetattr (0, TCSANOW, &new_settings); termios结构的描述了终端的模式,在这段代码中我们改变了它,使得终端能够接收到键盘输入马上返回。所以就能够使用一般的读取字符函数getchar ()来获得输入字符。 在退出你的程序时,要记得把终端环境改回来: tcsetattr (0, TCSANOW, &stored_settings);
这几个函数以及结构要求包含头文件termios.h和stdio.h。 下面是一个测试文件,可以在Windows和Linux操作系统下,编译运行:
#include "stdio.h" #include "stdlib.h" #ifdef _WIN32 //Linux platform #include "conio.h" #define get_char getch #else #include "termios.h" #define get_char getchar #endif
int main (int argc, char* argv[]) { #ifdef _WIN32 //Do nothing #else struct termios stored_settings; struct termios new_settings; tcgetattr (0, &stored_settings); new_settings = stored_settings; new_settings.c_lflag &= (~ICANON); new_settings.c_cc[VTIME] = 0; new_settings.c_cc[VMIN] = 1; tcsetattr (0, TCSANOW, &new_settings); #endif while (1) { char c = get_char (); if ('q' == c || 'Q' == c) break; printf ("You input: %c\n", c); } #ifdef _WIN32 //Do nothing #else tcsetattr (0, TCSANOW, &stored_settings); #endif return 0; } 要提的一点是,getch ()是没有回显的,而getchar ()是有回显的,所以在Windows和Linux下的运行有点不同。

|