輸入一個字符,判斷其屬於:英文字母、數字字符、其他字符。
#include <stdio.h>
#include <ctype.h> // 提供 isalpha, isdigit 等
int main() {
char ch;
printf("請輸入一個字符: ");
scanf(" %c", &ch); // 格式串前空格跳過空白/換行
if (isalpha(ch)) {
printf("'%c' 是英文字母\n", ch);
} else if (isdigit(ch)) {
printf("'%c' 是數字字符\n", ch);
} else {
printf("'%c' 是其他字符\n", ch);
}
return 0;
}
| 函數 | 判斷條件 | 備註 |
|---|---|---|
isalpha(c) | 字母 (A-Z, a-z) | 區分大小寫 |
isupper(c) | 大寫字母 (A-Z) | |
islower(c) | 小寫字母 (a-z) | |
isdigit(c) | 數字字符 (0-9) | |
isalnum(c) | 字母或數字 | isalpha||isdigit |
isspace(c) | 空白字符 (空格、\n、\t、\v、\f、\r) | |
ispunct(c) | 標點符號 (非字母數字、非空白的可打印字符) | |
isprint(c) | 可打印字符 (含空格) | |
iscntrl(c) | 控制字符 (ASCII 0-31, 127) | |
isxdigit(c) | 十六進制數字 (0-9, A-F, a-f) |
// 僅適用 ASCII 兼容字符集
if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'))
puts("字母");
else if (ch >= '0' && ch <= '9')
puts("數字");
else
puts("其他");
⚠️ **缺點**:不支援 EBCDIC 等非 ASCII 字符集,可移植性差。**生產代碼務必用 ctype.h**。
if (ch >= 'a' && ch <= 'z' || ch >= 'a' && ch <= 'z') 重複判斷小寫,漏掉大寫。正確應包含兩段範圍。scanf("%c", &ch) 會讀到上一輪殘留的 \n,導致誤判為「其他」。**必須 scanf(" %c", &ch)**。ctype.h 函數參數為 int,但傳 char 會自動提升,無需轉換。若 char 為有符號且負值,需轉 unsigned char 避免 UB:isalpha((unsigned char)ch)。void analyze(const char *s) {
int alpha=0, digit=0, other=0;
for (; *s; s++) {
if (isalpha(*s)) alpha++;
else if (isdigit(*s)) digit++;
else other++;
}
printf("字母:%d 數字:%d 其他:%d\n", alpha, digit, other);
}
ctype.h**:isalpha/isdigit 標準、可移植、區域感知(配合 setlocale)。scanf(" %c", &ch) 格式串前空格**必加**,跳過空白字符。