#include <stdio.h>
int main() {
int num = 0, space = 0, other = 0;
int ch;
printf("輸入一行文字: ");
while ((ch = getchar()) != '\n' && ch != EOF) {
if (ch >= '0' && ch <= '9') num++;
else if (ch == ' ') space++;
else other++;
}
printf("數字: %d, 空白: %d, 其他: %d\n", num, space, other);
return 0;
}
ctype.h 標準庫函數 (更健壯、可移植)#include <stdio.h>
#include <ctype.h>
int main() {
int num = 0, space = 0, other = 0;
char str[1000];
printf("輸入字串: ");
fgets(str, sizeof(str), stdin); // 含換行
for (char *p = str; *p; ++p) {
if (isdigit(*p)) num++;
else if (isspace(*p)) space++; // 涵蓋空格、定位鍵、換行等
else other++;
}
printf("數字: %d, 空白: %d, 其他: %d\n", num, space, other);
return 0;
}
| 項目 | 方法一 | 方法二 |
|---|---|---|
| 空白判斷 | 僅空格 ' ' | 所有空白字元 (isspace) |
| 輸入方式 | 逐字元 getchar | 整行 fgets |
| 跨平台 | ASCII 相容即可 | 標準 C,支援多國字元集 |
| 程式碼長度 | 較短 | 稍長 |
教學初期可用方法一理解 ASCII 碼邏輯;實務專案強烈建議方法二,利用標準庫處理地區設定與特殊空白字元。