liu13610 2015-01-07 14:06 采纳率: 100%
浏览 3353
已采纳

判断每个字母在string中出现的次数

写了一个c++程序判断每个字母在string中出现的次数 但为什么无论输入什么,全部字母都显示出现0次?
#include
#include
using namespace std;

int count(const char * const s)
{
int
count = new int[26];
for (int i = 0; i < 26; i++)
count[i] = 0;

for (int j = 0; j < strlen(s); j++)
{
    count[s[j] - 'a']++;
}

return count;

}

int main()
{
char str[100]; //100 is big enough to contain the string
cin >> str[100];
int* p = count(str);
for (int a = 'a'; a <= 'z'; a++)
{
cout << (char)(a) << ": " << p[a - 'a'] << " times" << endl;
}
return 0;
}

  • 写回答

4条回答 默认 最新

  • ForestDB 2015-01-08 01:45
    关注

    cin >> str[100]
    1. 只是接受一个输入的字符,因为str[100]是char,而str才是指向char array的指针,cin对这两种类型处理是不一样的(即所谓重载);
    2. str[100]越界了,str[99]是最大的可访问区域;
    3. count是new出来的,返回后没有delete。

    友情提醒:好好看书。

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

报告相同问题?

悬赏问题

  • ¥15 关于#网络安全#的问题:求ensp的网络安全,不要步骤要完成版文件
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥20 使用Photon PUN2解决游戏得分同步的问题
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序