题目
从标准输入读入一行文本字符,统计并输出其中英文字母、数字字符、空格字符以及其他字符的个数。
输入格式:输入一行包含各种字符的文本字符串(以换行符结束)。
输出格式:分行或按格式输出四类字符的统计数量:letters=数量 digits=数量 spaces=数量 others=数量。
数据范围与约定:字符串长度不超过 1000 字符。
思路与算法
1. 逐字符流式读取
使用 getchar() 循环读取字符,直到遇到 \n 或 EOF 为止。
2. 字符分类判断
利用标准库 <ctype.h> 的辅助函数:
英文字母:isalpha(c);
数字:isdigit(c);
空白:isspace(c) 或 c == ' ';
其余字符落入 else 计数。
完整程序
#include <stdio.h>
#include <ctype.h>
int main(void)
{
int letters = 0, digits = 0, spaces = 0, others = 0;
int ch;
// 逐字符读入整行,直到换行符或文件末尾
while ((ch = getchar()) != '\n' && ch != EOF) {
// 利用 ctype.h 标准库函数分类判断
if (isalpha(ch)) {
letters++;
} else if (isdigit(ch)) {
digits++;
} else if (isspace(ch)) {
spaces++;
} else {
others++;
}
}
printf("letters:%d\n", letters);
printf("digits:%d\n", digits);
printf("spaces:%d\n", spaces);
printf("others:%d\n", others);
return 0;
}运行示例
输入:
Hi 2026!输出:
letters:2
digits:4
spaces:1
others:1