需求:阻塞等待鍵盤輸入,超時後自動返回。Windows 控制台程序可用 _kbhit() (或 kbhit()) 非阻塞檢測鍵盤狀態。
_kbhit():若鍵盤緩衝區有字符返回非 0,否則立即返回 0 (不阻塞)。_getch() / _getche():讀取單字符 (不回顯/回顯)。#include <conio.h> // _kbhit, _getch
#include <ctime> // clock
// 返回 true 表示讀到字符,ch 輸出字符;false 表示超時
bool timedGetChar(char& ch, int timeoutMs) {
clock_t start = clock();
while (true) {
if (_kbhit()) {
ch = _getch();
return true;
}
if (static_cast<clock_t>(clock() - start) * 1000 / CLOCKS_PER_SEC >= timeoutMs)
return false;
// 可選:Sleep(10) 降低 CPU 佔用
}
}
// 使用示例
int main() {
char ch;
cout << "等待輸入 3 秒...";
if (timedGetChar(ch, 3000)) {
cout << "\n讀到字符: " << ch << endl;
} else {
cout << "\n超時,無輸入。" << endl;
}
return 0;
}
conio.h 提供 _kbhit/_getch。termios) + select/poll 監聽 stdin。
std::cin 非阻塞檢查,目前仍需平台相關代碼。#include <termios.h>, <unistd.h>, <fcntl.h>, <sys/time.h>
bool kbhit_linux() {
struct termios oldt, newt;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
int oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);
int ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
fcntl(STDIN_FILENO, F_SETFL, oldf);
if (ch != EOF) { ungetc(ch, stdin); return true; }
return false;
}
Windows 下 _kbhit() 是實現帶超時鍵盤輸入的標準方案。