程序是人機交互的媒介,有輸出必有輸入。C 語言提供多種從鍵盤獲取用戶輸入的函數:
scanf():格式化輸入,支援多種數據類型,最靈活、最常用。getchar()、getche()、getch():輸入單個字符,行為略有差異。gets():讀取整行並作為字符串處理。scanf() 雖強大,但無法完全取代其他函數,各有適用場景。
scanf 是 scan format 縮寫,意為「格式化掃描」。先看基礎示例:
#include <stdio.h>
#include <stdlib.h>
int main() {
int a, b, c, d;
scanf("%d", &a); // 輸入整數賦值給 a
scanf("%d", &b); // 輸入整數賦值給 b
printf("a+b=%d\n", a+b);
scanf("%d %d", &c, &d); // 同時輸入兩個整數
printf("c*d=%d\n", c*d);
system("pause");
return 0;
}
運行結果:
12↙
60↙
a+b=72
10 23↙
c*d=230
↙ 表示按下回車鍵。每按一次回車,scanf() 讀取並提取數據。
scanf("%d %d", &a, &b); // 變量前必須加 &
printf("%d %d", a, b); // 輸出不需要 &
& 稱為「取地址符」,獲取變量在內存中的地址。scanf 根據地址將讀取的數據寫入內存。這與 printf 形成鮮明對比。
#include <stdio.h>
#include <stdlib.h>
int main() {
int a = 'F', b = 12, c = 452;
printf("&a=%#x, &b=%#x, &c=%#x\n", &a, &b, &c);
system("pause");
return 0;
}
輸出:
&a=0x18ff48, &b=0x18ff44, &c=0x18ff40
注意:這是虛擬地址,非物理內存地址,現代作業系統為內存管理引入的概念。
scanf("%d %d", &a, &b); // 空格分隔
scanf("%d, %d, %d", &a, &b, &c); // 逗號分隔
scanf("%d is bigger than %d", &a, &b); // 字符串分隔
scanf 對輸入數據間空白字符的處理較寬鬆,多個空格、換行、Tab 均視為分隔符;但若格式字符串包含非空白字符(如逗號、特定單詞),輸入必須嚴格匹配。
一次性輸入多個值:
12 60 10 23↙
a+b=72
c*d=230
scanf 會保留緩衝區中未讀取的內容供下次使用。但若格式不匹配,可能導致後續 scanf 被「跳過」:
scanf("a=%d", &a); // 輸入 a=100↙
scanf("b=%d", &b); // 此句被忽略,b 保持初值 0
這涉及 C 語言輸入緩衝區機制,後續專題詳細講解。
#include <stdio.h>
#include <stdlib.h>
int main() {
char c = getchar();
printf("c='%c'\n", c);
system("pause");
return 0;
}
運行:#↙ → c='#'
必須按回車確認,有回顯(輸入字符顯示在屏幕)。
#include <stdio.h>
#include <conio.h> // 需此頭文件
#include <stdlib.h>
int main() {
char c = getche();
printf("c='%c'\n", c);
system("pause");
return 0;
}
運行:# → c='#'
輸入即獲取,無需回車,有回顯。conio.h 非標準頭文件,移植性較差。
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
int main() {
char c = getch();
printf("c='%c'\n", c);
system("pause");
return 0;
}
運行:輸入 # 無顯示 → c='#'
無回顯,適合輸入密碼等敏感信息。
本質上,getch()/getche()無緩衝即時響應;getchar()帶緩衡需回車確認。getchar()屬標準 C(stdio.h),前兩者屬擴展(conio.h),不保證所有編譯器支援。
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
int main() {
char str1[30], str2[30];
gets(str1); // 讀取整行(含空格)
scanf("%s", str2); // 遇空格停止
puts(str1);
puts(str2);
system("pause");
return 0;
}
運行:
The world is beautiful!↙
Hello World!↙
The world is beautiful!
Hello
gets() 讀取整行含空格;scanf("%s") 遇空格截斷。注意:gets() 不安全(無長度檢查),現代 C 建議用 fgets() 替代。