輸入一行字符,分別統計英文字母、空格、數字、其他字符的個數。
#include <stdio.h>
#include <ctype.h> // isalpha, isdigit, isspace
int main(void) {
char line[1024];
printf("請輸入一行字符: ");
if (!fgets(line, sizeof(line), stdin)) return 0;
int letters = 0, digits = 0, spaces = 0, others = 0;
for (char *p = line; *p; ++p) {
if (isalpha((unsigned char)*p)) letters++;
else if (isdigit((unsigned char)*p)) digits++;
else if (isspace((unsigned char)*p)) spaces++;
else others++;
}
printf("字母: %d, 數字: %d, 空格: %d, 其他: %d\n",
letters, digits, spaces, others);
return 0;
}
ctype.h)
for (char *p = line; *p; ++p) {
char ch = *p;
if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) letters++;
else if (ch >= '0' && ch <= '9') digits++;
else if (ch == ' ' || ch == '\t' || ch == '\n') spaces++;
else others++;
}
fgets 讀整行,保留空格、制表符;scanf("%s") 會跳過空白,不適用。ctype.h 函數要求參數為 unsigned char 或 EOF,故轉換 (unsigned char)*p 避免負值未定義行為。fgets 會保留末尾 \n,統計空白時包含它;若不想算,可在循環前 line[strcspn(line, "\n")] = 0; 去除。