首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C語言經典實例:_getch 即時鍵盤監聽與輸入驗證

     編輯:關於C語言

程式功能

使用 _getch() (非標準,Windows conio.h) 實現**無緩衝、無回顯**的即時鍵盤讀取,驗證用戶輸入僅為 'Y'/'N' (大小寫不敏感),否則蜂鳴器報警並重新讀取。

完整代碼 (Windows 專用)

#include <stdio.h>
#include <conio.h>      // _getch, _putch
#include <stdlib.h>     // system
#include <ctype.h>      // toupper

int main() {
    char letter;
    printf("Do you want to continue? (Y/N): ");
    
    letter = _getch();           // 即時讀取單字符,無需 Enter
    letter = toupper(letter);    // 統一轉大寫
    
    // 輸入驗證迴圈
    while(letter != 'Y' && letter != 'N') {
        _putch(7);               // ASCII 7 = BEL (蜂鳴)
        letter = _getch();
        letter = toupper(letter);
    }
    
    printf("\nYour response was %c\n", letter);
    system("pause");             // Windows 專用暫停
    return 0;
}

跨平台替代方案

平台頭文件無緩衝讀取蜂鳴
Windowsconio.h_getch()_putch(7) 或 Beep()
Linux/Unixtermios.h, unistd.h設置終端原始模式 + read(STDIN_FILENO, &c, 1)write(STDOUT_FILENO, "\a", 1)
跨平台ncursesgetch() (ncurses 模式)beep()

Linux 原始模式實作範例

#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <ctype.h>

int getch_raw() {
    struct termios oldt, newt;
    int ch;
    tcgetattr(STDIN_FILENO, &oldt);
    newt = oldt;
    newt.c_lflag &= ~(ICANON | ECHO);  // 關閉標準模式與回顯
    tcsetattr(STDIN_FILENO, TCSANOW, &newt);
    ch = getchar();
    tcsetattr(STDIN_FILENO, TCSANOW, &oldt);  // 恢復
    return ch;
}

int main() {
    char c;
    printf("Continue? (Y/N): ");
    c = toupper(getch_raw());
    while(c != 'Y' && c != 'N') {
        putchar('\a');  // 蜂鳴
        c = toupper(getch_raw());
    }
    printf("\nResponse: %c\n", c);
    return 0;
}

關鍵函式說明

  • _getch():直接從鍵盤硬體讀取,不經 stdin 緩衝區,**無回顯**,適用密碼輸入、遊戲控制、選單導航
  • _putch(c):直接輸出到控制台,不經 stdout 緩衝區
  • toupper(c):<ctype.h>,處理大小寫不敏感比較
  • system("pause"):Windows 專用,等待按鍵繼續

應用場景擴展

  • **密碼輸入**:_getch() + 顯示 '*' 回顯
  • **遊戲鍵盤控制**:即時響應 WASD/方向鍵
  • **單鍵選單**:無需按 Enter 確認
  • **即時監控儀表板**:熱鍵切換視圖

總結

_getch() 是 Windows 控制台程式實現即時互動的關鍵工具。跨平台開發時,應封裝平台差異:#ifdef _WIN32 ... #else ... #endif,或使用 ncurses 等成熟庫。理解終端「標準模式」與「原始模式」的切換,是掌握控制台交互編程的基石。

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