我即将完成我的代码!我可以使用一些帮助,我写了一个程序来计算字符串中的字母数。在输出我的数据时,我的问题最终出现了。说我输入字符串“AAAABBBC”
我的预期输出应该是 A-4 B-3 C-1
相反,我得到了 C-4 C-3 C-1任何帮助将不胜感激,我的代码在下面
#include <iostream>
using namespace std;
class moose
{
char inputbuffer[122];
char countbuffer[122];
long count;
short index = 0;
public:
char charcount();
char charinput();
char initialize();
};
int main()
{
moose obj;
obj.initialize();
obj.charinput();
obj.charcount();
system("pause");
}
char moose::initialize()
{
for (int i = 0; i < 122; i++)
countbuffer[i] = 0;
return 0;
}
char moose::charinput()
{
cout << "Enter your text and I'll read your characters" << endl;
cin.getline(inputbuffer, 132);
cin.gcount();
count = cin.gcount();
count--;
return 0;
}
char moose::charcount()
{
for (int i = 0; i < count; i++)
{
if (inputbuffer[i] >= 'a' & inputbuffer[i] <= 'z' || inputbuffer[i] >= 'A' & inputbuffer[i] <= 'Z' || inputbuffer[i] > '0' & inputbuffer[i] <= '9'){
index = inputbuffer[i];
countbuffer[index]++;
}
}
for (int i = 0; i <= 122; i++) {
if (countbuffer[i] > 0)
{
cout << char(index) << " - " << int(countbuffer[i]) << endl;
}
}
return 0;
}
答案 0 :(得分:2)
char moose::charcount()
{
for (int i = 0; i < count; i++)
{
if (inputbuffer[i] >= 'a' && inputbuffer[i] <= 'z' || inputbuffer[i] >= 'A' && inputbuffer[i] <= 'Z' || inputbuffer[i] > '0' && inputbuffer[i] <= '9'){
index = inputbuffer[i];
countbuffer[index]++;
}
}
for (int i = 0; i <= 122; i++) {
if (countbuffer[i] > 0)
{
cout << char(i) << " - " << int(countbuffer[i]) << endl;
}
}
return 0;
}
答案 1 :(得分:1)
修改最后一个循环,如下所示:
for (int i = 0; i <= 122; i++) {
if (countbuffer[i] > 0)
{
cout << char(i) << " - " << int(countbuffer[i]) << endl;
}
}
并在第一个循环中将bitwise和ss转换为逻辑和(使用&amp;&amp;)。
顺便说一句,在你的情况下,最好使用像unordered_map这样的STL容器,因为你要实际构建一个字符直方图。如果你要存储一般字符的频率,那么分配一个由所有可能的字符索引的数组是很浪费的,因为最后很多条目都是0。