使用者按鍵瞬間顯示轉換後字符,**無需按 Enter**,即「原始模式」輸入。標準 getchar/scanf 為行緩衝,無法滿足。
conio.h)#include <stdio.h>
#include <conio.h> // _getch, _putch
#include <ctype.h> // toupper, tolower
int main() {
int ch;
puts("輸入字符 (ESC 退出):");
while ((ch = _getch()) != 27) { // 27 = ESC
if (ch >= 'A' && ch <= 'Z') // 大寫轉小寫
ch = ch - 'A' + 'a';
else if (ch >= 'a' && ch <= 'z') // 小寫轉大寫 (題目反向也可)
ch = ch - 'a' + 'A';
_putch(ch); // 直接輸出到控制台
}
putchar('\n');
return 0;
}
termios)#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <ctype.h>
int main() {
struct termios oldt, newt;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO); // 關閉標準模式與回顯
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
int ch;
puts("輸入字符 (ESC 退出):");
while ((ch = getchar()) != 27) {
if (ch >= 'A' && ch <= 'Z') ch = tolower(ch);
else if (ch >= 'a' && ch <= 'z') ch = toupper(ch);
putchar(ch);
fflush(stdout); // 強制刷新
}
tcsetattr(STDIN_FILENO, TCSANOW, &oldt); // 恢復終端
putchar('\n');
return 0;
}
// raw_input.h
#ifndef RAW_INPUT_H
#define RAW_INPUT_H
int raw_getchar(void); // 非阻塞/阻塞可配置
void raw_putchar(int c);
void raw_mode_enter(void);
void raw_mode_exit(void);
#endif
// raw_input.c 內部用 #ifdef _WIN32 區分實現
fflush(stdin) **未定義行為** (C 標準僅定義輸出流刷新),Windows 偶然有效但不可移植。getch() 非標準,_getch() 為 MSVC 具體實現,MinGW 也提供。SIGINT) 需在退出前恢復終端屬性,否則終端會「卡死」。kbhit() / select())。