(已解决)字符串分类统计 c语言 问题

这是题目
输入一行字符,分别统计出其中英文字母、数字、空格和其他字符的个数。

这是我的代码

#include <stdio.h>
#include <string.h>

int main ()
{
    char str[201];
    int i, zm = 0, sz = 0, bd = 0, kg = 0;
    scanf("%s", str);
    for(i = 0; i < strlen(str); i++)
    {
        if('a' <= str[i] && str[i] <= 'z' || 'A' <= str[i] && str[i] <= 'Z') zm++;
        else if(str[i] == ' ') kg++;
        else if('0' <= str[i] && str[i] <= '9') sz++;
        else bd++;
    }
    printf("%d %d %d %d", zm, sz, kg, bd);
    return 0;
}

就是通不过,好像是因为第一个空格后的字符全部都扫描不到,但不知道是为什么?

最佳答案

change scanf("%s", str); to scanf("%[^\n]", str);

1年前 评论
讨论数量: 2

change scanf("%s", str); to scanf("%[^\n]", str);

1年前 评论
长日将尽

scanf 读入字符串不会包含空格。scanf 的行为是:先跳过空格,然后根据格式串(如:%s)匹配字符,遇到空格就结束匹配。

要想读取一行输入,可以自定义一个读取一行输入到 char str[] 的函数,函数内部使用 getchar() 循环读入输入的字符,直到遇到 \n 或者读入的字符数超出给定的字符数组的长度。

1年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!