很多 C 語言初學者在使用 scanf("%c", &ch) 讀取單個字符時,發現輸入字符並按下回車後,程序並沒有立即輸出結果,光標只是跳到下一行開頭。這其實是因為 scanf 讀取字符時會將回車符(\n)留在輸入緩衝區中,導致後續邏輯異常。
#include <stdio.h>
int main(void) {
char ch;
printf("Please enter a character.\n");
scanf("%c", &ch);
printf("The code for %c is %d.\n", ch, ch);
return 0;
}
推薦使用 getchar() 替代 scanf("%c", ...),它會自動處理換行符,代碼更簡潔健壯:
#include <stdio.h>
int main(void) {
char ch;
printf("Please enter a character.\n");
ch = getchar();
printf("The code for %c is %d.\n", ch, ch);
return 0;
}
若必須使用 scanf,可在格式字符串前加空格 scanf(" %c", &ch) 跳過空白字符,或調用 getchar() 額外讀取一次換行符。理解輸入緩衡區機制是避免此類問題的關鍵。