輸入 aaaa,預期「字母數=4」,實際輸出「其他字符數=4」。
isalpha(ch) 返回值規則:
if (isalpha(a) == 1),小寫字母返回 2,條件為假,進入 else 分支計為「其他」。// 方式一:利用 C 非零即真特性(推薦)
if (isalpha(a)) x++;
else if (isdigit(a)) y++;
else z++;
// 方式二:顯式判斷非零
if (isalpha(a) != 0) x++;
// 方式三:針對大小寫分開統計
if (isalpha(a) == 1) upper++;
else if (isalpha(a) == 2) lower++;
C 標準規定
isalpha、isdigit等返回非零表示真,零表示假,具體非零值由實現定義(常見:大寫 1、小寫 2)。切勿與具體數值比較。
#include <stdio.h>
#include <ctype.h>
int main() {
char ch;
int letters = 0, digits = 0, others = 0;
while ((ch = getchar()) != '\n') {
if (isalpha(ch)) letters++;
else if (isdigit(ch)) digits++;
else others++;
}
printf("字母:%d,數字:%d,其他:%d\n", letters, digits, others);
return 0;
}