我正在编写一个c ++程序来检查字母的频率。当输出没有像“aabbbsssd”这样的空格时,我的代码可以准确地检查字母的频率。但是,如果输入的空间如下:“do be do bo。”我的输出只是 “d 1”和“o 1”,没有“b”和“e”的频率。
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
struct Letters
{
Letters() : freq(0){}
Letters(char letter,int freq) {
this->freq = freq;
this->letter = letter;
}
char letter;
int freq;
};
bool Greater(const Letters& a, const Letters& b)
{
if(a.freq == b.freq)
return a.letter < b.letter;
return a.freq > b.freq;
}
int main () {
cout<<"Enter text:" << endl;
string input;
getline(cin, input);
vector<Letters> count;
int letters[26]= {0};
for (int x = 0; x < input.length(); x++) {
if (isalpha(input[x])) {
int c = tolower(input[x] - 'a');
letters[c]++;
}
}
for (int x = 0; x < 26; x++) {
if (letters[x] > 0) {
char c = x + 'a';
count.push_back(Letters(c, letters[x]));
}
}
std::sort(count.begin(),count.end(),Greater);
cout<<"Frequencies:" << endl;
for (int x = 0 ; x < count.size(); x++) {
cout<<count[x].letter << " " << count[x].freq<<"\n";
}
return 0;
}
如果写得不好而道歉,并提前感谢您的帮助!
答案 0 :(得分:1)
答案 1 :(得分:0)
假设测试程序的人也输入大写文本,您的程序应如下所示:
#include <iostream>
#include <iomanip>
using namespace std;
int alpha[26] = {0};
int main(void)
{
string text;
cout << "Enter text:" << endl;
getline(cin, text);
for (int i = 0; i < text.length(); i++)
{
int a = text[i];
if (a >= 'A' && a <= 'Z')
{
alpha[a - 'A']++;
}
else if (a >= 'a' && a <= 'z')
{
alpha[a - 'a']++;
}
}
cout << "Frequencies:" << endl;
for (int i = 0; i < 26; i++)
{
if (alpha[i])
{
cout << right << char('a' + i) << setw(2) << right << alpha[i] << endl;
}
}
return 0;
}
答案 2 :(得分:0)
好吧,cin只会读入空格分隔符并读取整行,你需要使用getline(cin,v);其中v是你想把输入放在里面的变量。