7-1 统计字符串中字母、数字、空格和其他字符的个数 (5分)运行超时

统计字符串中字母、数字、空格和其他字符的个数。
输入格式:

在一行中输入长度不超过40的字符串。
输出格式:

第一行中输出“zimu=x“

第二行中输出“shuzi=y“

第三行中输出“kongge=z”,

第四行中输出“qita=m” 所有结果均原样输出,没有列宽控制。
输入样例:

sd$2h b57 sA

输出样例:

zimu=6
shuzi=3
kongge=2
qita=1

我的代码:

#include <iostream>
using namespace std;
int main(){
    char a;
    int zm=0,sz=0,kg=0,qt=0;
         while ((a=getchar())!='\n')
         {
        if (a>='a'&&a<='z'||a>='A'&&a<='Z'){
            zm++;
        }
        else if (a>='0'&&a<='9'){
            sz++;
        }
        else if(a==' '){
            kg++;
        }
        else
            qt++;
    }
    cout<<"zimu="<<zm<<endl;
    cout<<"shuzi="<<sz<<endl;
    cout<<"kongge="<<kg<<endl;
    cout<<"qita="<<qt<<endl;
}

这咋会超时了呢

你的程序没有看出什么问题,但是你修改为下面的看看

#include <iostream>
using namespace std;
int main(){
    char a;
    int zm=0,sz=0,kg=0,qt=0;
    char input[50];
    scanf("%[^\n]", input);
    int i = 0;
         while ((a=input[i++])!=0)
         {
        if (a>='a'&&a<='z'||a>='A'&&a<='Z'){
            zm++;
        }
        else if (a>='0'&&a<='9'){
            sz++;
        }
        else if(a==' '){
            kg++;
        }
        else
            qt++;
    }
    cout<<"zimu="<<zm<<endl;
    cout<<"shuzi="<<sz<<endl;
    cout<<"kongge="<<kg<<endl;
    cout<<"qita="<<qt<<endl;
}

可能是测试的最后不是\n,改成\0试试