首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C++ 非阻塞鍵盤輸入帶超時:使用 _kbhit() 輪詢實現

     編輯:程式設計綜合問答

需求:阻塞等待鍵盤輸入,超時後自動返回。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;
}

跨平台考量

  • Windows:conio.h 提供 _kbhit/_getch。
  • 2. Linux/Unix:需設置終端非規範模式 (termios) + select/poll 監聽 stdin。
  • C++26 可能引入標準化的 std::cin 非阻塞檢查,目前仍需平台相關代碼。

Linux 簡易實現 (參考)

#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() 是實現帶超時鍵盤輸入的標準方案。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved