1

我是 C++ 的新手,我想做的是计算一个字母与一段文本或段落一起出现的次数,并将其存储到一个称为频率数组的数组中。

下面的代码在一定程度上起作用,如果用户键入 hello frequencyarray stores 11121,如果用户键入 aaba frequencyarray stores 1213,我不想要运行总数,我希望数组存储 1121 和 31。因此,如果出现相同的字母,它会将 1 添加到数组中。

谢谢大卫

#include <iostream> //for cout cin
#include <string>   //for strings
#include <fstream>  //for files

using namespace std;

int main()
{       
    string text;

    int frequencyarray [26]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

    cout << "Enter Word: ";
    cin >> text;

//***************************COUNT OCCURANCES************************

    for (int i(0); i < text.length(); i++)
    {
        char c = text[i];

        c = toupper(c);
        c -= 65;

        if (c < 26 || c >=0)
        {
            frequencyarray[c]++;
            cout << frequencyarray[c];
        }
    }

    system ("pause");

return(0);

}`
4

2 回答 2

2

如果您不想要运行总数,请不要cout << freqencyarray[c];在循环内部计算出现次数。

于 2013-04-18T16:35:32.600 回答
0

尝试这个

#include <iostream> //for cout cin
#include <string>   //for strings
#include <fstream>  //for files
#include <algorithm>

using namespace std;

int main()
{       
    string text;

    int frequencyarray [26]={0};

    cout << "Enter Word: ";
    cin >> text;

//***************************COUNT OCCURANCES************************

    for (int i(0); i < text.length(); i++)
    {
        char c = text[i];

        c = toupper(c);
        c -= 65;

        if (c < 26 || c >=0)
        {
            frequencyarray[c]++;
        }
    }

    std::for_each(std::begin(frequencyarray), std::end(frequencyarray), [](int i)
    {
         std::cout << i << ",";
    });
    std::cout << "\n";
    system ("pause");

return(0);

}
于 2013-04-18T16:46:14.593 回答