忧默的小男孩 2022-09-05 17:28 采纳率: 94.4%
浏览 50
已结题

关于c++字符串的问题

第一段代码不知道为什么会出现segmentation fault,我感觉我写的也没有什么问题吧,是a.size()用的不对吗?后来我把第二个for循环的条件循环条件给改了,不知道为什么又出现了一些莫名其妙的错误?

img

img

img


#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>

using namespace std;

int main(){
    int n;
    cin >> n;
    int count[60];    //小写字母a的ascii值为65,大写字母Z的ascii值为122,122-65=57,所以数组最大为57,开60完全没有毛病啊
    while(n--){
        string a;
        getline(cin,a);
        for(int i=0;i<a.size()-1;i++){
            count[a[i]-'a']++;
        }
            int max=count[0],x=0;
        for(int i=0;i<60;i++){
            if(count[i]=='\0') break;
            if(count[i]>max) 
                 x=i;
                max=count[i];
        }
           
            cout << " " << max;
    }
}

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>

using namespace std;

int main(){
    int n;
    cin >> n;
    int count[60];    //小写字母a的ascii值为65,大写字母Z的ascii值为122,122-65=57,所以数组最大为57,开60完全没有毛病啊
    while(n--){
        string a;
        getline(cin,a);
        for(int i=0;i<a.size()-1;i++){
            count[a[i]-'a']++;
        }
            int max=count[0],x=0;
        for(int i=0,strlen(count);i<len;i++){
            if(count[i]=='\0') break;
            if(count[i]>max) 
                 x=i;
                max=count[i];
        }
           
            cout << " " << max;
    }
}
  • 写回答

7条回答 默认 最新

  • CSDN专家-sinJack 2022-09-05 17:33
    关注

    题目并没说只输入小写字符吧,如果是大写字符或者其他字符的话,会导致数组越界异常。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 9月7日
  • 已采纳回答 9月5日
  • 创建了问题 9月5日

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line