輸入一行字符,分別統計其中英文字母、空格、數字和其他字符的個數。輸入以換行符 '\n' 結束。
使用 while 迴圈逐字符讀取,利用 ASCII 碼範圍判斷字符類型:
'a'~'z' 或 'A'~'Z''0'~'9'' '四個計數器分別累加,最後格式化輸出。
#include <stdio.h>
int main() {
char c;
int letters = 0, spaces = 0, digits = 0, others = 0;
printf("請輸入一行字符:\n");
while ((c = getchar()) != '\n') {
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
letters++;
else if (c >= '0' && c <= '9')
digits++;
else if (c == ' ')
spaces++;
else
others++;
}
printf("letters=%d, digits=%d, spaces=%d, others=%d\n",
letters, digits, spaces, others);
return 0;
}
可使用 ctype.h 中的 isalpha()、isdigit()、isspace() 標準庫函數,提高可讀性與可移植性。注意 getchar() 返回 int,可正確處理 EOF。