輸入一行字符,分別統計其中英文字母、空格、數字和其他字符的個數。
getchar() 循環讀取,直到遇到換行符 '\n''A'~'Z' (65~90) 或 'a'~'z' (97~122)'0'~'9' (48~57)' ' (32)#include <stdio.h>
#include <ctype.h> // 推薦使用標準庫分類函數
int main(void) {
int c;
int letters = 0, spaces = 0, digits = 0, others = 0;
printf("請輸入一行字符(以 Enter 結束):\n");
while ((c = getchar()) != '\n' && c != EOF) {
if (isalpha(c)) letters++;
else if (isdigit(c)) digits++;
else if (c == ' ') spaces++;
else others++;
}
printf("統計結果:字母=%d 空格=%d 數字=%d 其他=%d\n",
letters, spaces, digits, others);
return 0;
}
ctype.h 標準函數(isalpha、isdigit 等),提高可讀性與可移植性(支持本地化字符集)c != EOF,防止輸入重定向文件時無限循環int 接收 getchar() 返回值,正確處理 EOFconio.h、getch(),純標準 C,跨平台編譯無警告wchar_t、getwchar)支持 Unicode這道經典練習不僅考察基本循環與條件判斷,更強調標準庫函數的正確使用與輸入邊界條件的健壯處理——這正是從「能跑通」邁向「工程級代碼」的關鍵一步。