從標準輸入讀取字符流 (直到 EOF),統計:
'0'~'9' 出現次數。\t、換行符 \n 等) 次數。#include <stdio.h>
#include <ctype.h> // 提供 isspace(), isdigit() 等字符分類函數
int main() {
int digit_count[10] = {0}; // 統計 0-9
int space_count = 0;
int other_count = 0;
int ch;
// getchar() 返回 int,可容納 EOF (-1) 與所有字符值 (0-255)
while ((ch = getchar()) != EOF) {
if (isspace(ch)) {
space_count++;
} else if (isdigit(ch)) {
digit_count[ch - '0']++; // 字符 '0'~'9' 連續編碼,減 '0' 得索引
} else {
other_count++;
}
}
printf("space = %d\n", space_count);
for (int i = 0; i < 10; i++) {
printf("%d : %d\n", i, digit_count[i]);
}
printf("other = %d\n", other_count);
return 0;
}
getchar() 返回 int:必須用 int 變量接收,否則 EOF (-1) 會被截斷為 255 (若 char 為無符號) 或 -1 (有符號),導致邏輯錯誤。ctype.h 字符分類函數:isspace() 檢測所有空白字符 (不只是空格),isdigit() 檢測十進制數字。它們接受 int 參數,行為定義良好。ch - '0' 利用 ASCII 碼連續性將數字字符映射到 0~9 索引,巧妙避免 switch 或多重 if。Ctrl+D 發送 EOF,Windows 終端 Ctrl+Z 後回車。輸入: Hello World 123!
輸出:
space = 1
0 : 0
1 : 1
2 : 1
3 : 1
4 : 0
5 : 0
6 : 0
7 : 0
8 : 0
9 : 0
other = 11
isalpha()、isupper()、islower()。mbrtowc 等寬字符函數,getchar 單字節讀取不適用。