在很多情況下,我們希望在控制臺下,按鍵盤字符,程序馬上反應而不是等待回車后才響應。
在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下的運行有點不同。