一道困惑我许久的疑惑

题目:输入一行字符,以回车键作为结束标志,分别统计出大写字母,小写字母,空格,数字和其他字符的个数,并输出结果?
下面解决方案显示的错误是什么意思?为什么我这代码运行不了?

img

你定义的i是一个字符,且在循环外,只会读取一个字符,并且你写的读取格式是字符串,所以报错。


#include<stdio.h>
#include<ctype.h>

int main() {
    int upper_count = 0, lower_count = 0, space_count = 0, digit_count = 0, other_count = 0;
    char c;
    printf("请输入一行字符:");
    while ((c = getchar()) != '\n') {
        if (isupper(c)) {
            upper_count++;
        } else if (islower(c)) {
            lower_count++;
        } else if (isspace(c)) {
            space_count++;
        } else if (isdigit(c)) {
            digit_count++;
        } else {
            other_count++;
        }
    }
    printf("大写字母个数:%d\n", upper_count);
    printf("小写字母个数:%d\n", lower_count);
    printf("空格个数:%d\n", space_count);
    printf("数字个数:%d\n", digit_count);
    printf("其他字符个数:%d\n", other_count);
    return 0;
}

代码解释:

isupper(c) 和 islower(c) 函数判断字符 c 是否是大写字母或小写字母,并分别统计这两类字符的个数。
isspace(c) 函数判断字符 c 是否是空格,并统计空格的个数。
isdigit(c) 函数判断字符 c 是否是数字,并统计数字的个数。
其他字符的个数则通过在所有其他情况之后统计得到。

以下答案引用自GPT-3大模型,请合理使用:

```#include <stdio.h> int main() { char str[100]; int i,j,c,num; printf("Please input a string:

"); gets(str); for(i=0;i<strlen(str);i++) { c=str[i]; if(c>='A'&&c<='Z') num++ ; else if(c>='a'&&c<='z') num++; else if(c==' ') num++; else if(c>='0'&&c<='9') num++; } printf("There are %d capital letters, %d small letters, %d whitespaces, %d numbers and %d other characters in the string.

",num,num,num,num,num); return 0; }```