题目

读入一行文本,统计字母、数字、空格与其他字符

思路

本题读入一行文本,统计字母、数字、空格及其他字符的个数。

getchar 逐个读字符直到换行或 EOF,用 ctype.hisalphaisdigitisspace 分类;不属于前三类的计入「其他」。

解题分析

逐字符用 ctype.h 分类,读到换行结束。其它字符是既非字母数字又非空白(标点算其它)。

完整程序

#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) {
        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