使用 _getch() (非標準,Windows conio.h) 實現**無緩衝、無回顯**的即時鍵盤讀取,驗證用戶輸入僅為 'Y'/'N' (大小寫不敏感),否則蜂鳴器報警並重新讀取。
#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;
}
| 平台 | 頭文件 | 無緩衝讀取 | 蜂鳴 |
|---|---|---|---|
| Windows | conio.h | _getch() | _putch(7) 或 Beep() |
| Linux/Unix | termios.h, unistd.h | 設置終端原始模式 + read(STDIN_FILENO, &c, 1) | write(STDOUT_FILENO, "\a", 1) |
| 跨平台 | ncurses | getch() (ncurses 模式) | beep() |
#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() + 顯示 '*' 回顯_getch() 是 Windows 控制台程式實現即時互動的關鍵工具。跨平台開發時,應封裝平台差異:#ifdef _WIN32 ... #else ... #endif,或使用 ncurses 等成熟庫。理解終端「標準模式」與「原始模式」的切換,是掌握控制台交互編程的基石。