錯誤代碼
int a;
scanf("%d", &a);
if (isalpha('a')) x++; // 永真:字符 'a' 恒為字母
else if (isdigit('a')) y++;
else z++;
問題分析
'a' 是字符字面量(ASCII 97),isalpha('a') 恒返回真(非零)。
- 變量
a 存儲用戶輸入的整數(如 5),但從未傳給判斷函數。
- 導致無論輸入何值,統計結果永遠是「字母數=1」。
正確寫法
int ch = getchar(); // 讀取單字符
// 或讀取字符串後逐字符判斷
char str[100];
scanf("%s", str);
for (int i = 0; str[i]; i++) {
if (isalpha(str[i])) x++;
else if (isdigit(str[i])) y++;
else z++;
}
關鍵點
- 單引號表示字符常量(
'a'、'5'),無引號表示變量(a、ch)。
ctype.h 函數參數類型為 int,實際接收 unsigned char 或 EOF,傳入 char 會自動提升。
- 若需判斷用戶輸入的字符類型,請讀取字符(
getchar/scanf("%c")),而非整數(%d)。
擴展:完整統計程序
#include <stdio.h>
#include <ctype.h>
int main() {
int ch, letters = 0, digits = 0, others = 0;
printf("輸入文本(Ctrl+Z/EOF 結束):\n");
while ((ch = getchar()) != EOF) {
if (isalpha(ch)) letters++;
else if (isdigit(ch)) digits++;
else others++;
}
printf("字母:%d,數字:%d,其他:%d\n", letters, digits, others);
return 0;
}