用过 Turbo C 的人大概知道 getch 这个函数,它的功能是可以马上读取到用户输入的一个键,而且也不会显示用户输入了什么。在 Unix 下实现该功能的代码如下:
/* Standard C header */
#include <stdio.h> /* for getchar(), printf() */
/* POSIX headers */
#include <termios.h> /* for tcxxxattr, ECHO, etc */
#include <unistd.h> /* for STDIN_FILENO */
int Getch(void);
int main(void)
{
printf("Press any key to continue...");
Getch();
return 0;
}
int Getch (void)
{
int ch;
struct termios oldt, newt;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ECHO|ICANON);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
return ch;
}
上述程序适用于 Unix、Linux 等支持 POSIX 标准的操作系统。
本文版权归 蚂蚁的 C/C++ 标准编程 以及 作者 Antigloss 共同所有,转载请注明原作者和出处。谢谢。