好菜的大学生 2020-04-01 09:38 采纳率: 25%
浏览 1996

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;
}

这咋会超时了呢

  • 写回答

2条回答

  • threenewbee 2020-04-01 09:44
    关注

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

    #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;
    }
    
    
    评论

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记