检测击键

我需要检测按键,而无需用户按Enter键。 什么是最优雅的方式?

即如果用户按下字母Q而没有按回车键 ,程序会执行某些操作。

在unix / posix中,执行此操作的标准方法是使用tcsetattr将输入置于非规范模式:

 #include  #include  : struct termios attr; tcgetattr(0, &attr); attr.c_lflag &= ~ICANON; tcsetattr(0, TCSANOW, &attr); 

有关更多详细信息,请参见termios(3)手册页(可能还有比您想知道的更多信息)。

据我所知,除了使用像ncurses这样提供getch(void)函数的库之外,没有好办法可以这么做。

注意:从stdio.h出现getchar(void)等待直到按下回车键然后输入你的字符,所以它不起作用。

在Windows中, 提供了函数_getch(void) ,可用于读取键击而不回显它们(如果需要,可以自己打印)。

 #include  #include  int main( void ) { int ch; puts( "Type '@' to exit : " ); do { ch = _getch(); _putch( ch ); } while( ch != '@' ); _putch( '\r' ); // Carriage return _putch( '\n' ); // Line feed }