0

这段代码的目的是取一个已经传入程序的文件,生成文件中每个字母的字母频率。在上面的代码中,我删除了标点符号并转换为小写字母。

#include<iostream>
#include<string>
#include<fstream>

using namespace std;

int main()
{
    string fileContent = "qr rqh zrxog kdyh eholhyhg lq wkh odvw bhduv ri wkh qlqhwhhqwk fhqwxub wkdw wklv";

    int count[26] =  { 0 }; // an array the size of the alphabet.

    for(int f = 0; f < fileContent.length(); f++) // run til the file end.
    {
            if(fileContent[f] == 32) // to take care of the spaces.
            {
                    f++; // also tried "continue;" and yeild different and also incorrect results.
            }

            if(fileContent[f] >= 48 && fileContent[f] <= 57) //take care of numbers.
            {
                    f++; // tried "continue;"
            }

            count[fileContent[f]]++;

    }

    for(int p = 0; p < 26; p++)
    {
            cout << char(p + 97) << ": " << count[p]  << endl;
    }
return 0;
}

当我运行这段代码时,我得到了一些准确的频率,以及一些非常不正确的频率(似乎所有其他结果都是错误的,但在几个字母之后它会变成天文数字)。有什么办法可以更好地做到这一点?这段代码有什么问题?根据要求,我添加了更多代码(包括一个带有随机 100 的字符串),因为它显然不够清楚)

有关更多上下文,该程序适用于我正在研究的 Ceasar 移位解码器。我使用基本的 C++,非常感谢您更有经验的开发人员的任何建议。谢谢你!

4

2 回答 2

0

在您的程序中,此语句:

count[fileContent[f]]++;

应该:

count[fileContent[f]-97]++; //Assuming that all alphabets are in lowercase

如果你不这样做-97,它试图增加数组索引fileContent[f]处的值count,这可能超出了count数组的限制。

另外,请确保continue在两个if块中都进行,并且不需要像在循环中那样f++在两个块中显式地执行您已经在执行的操作。ifforf++

于 2017-11-03T02:46:14.947 回答
0

您正在以困难的方式做事:在代码中使用 C 风格的数组、幻数,并且到处冒着缓冲区溢出的风险。

将您的代码与此进行比较:

#include <string>
#include <iostream>
#include <map>
using namespace std;

int main()
{
    string fileContent = "qr rqh zrxog kdyh eholhyhg lq wkh odvw bhduv ri wkh qlqhwhhqwk fhqwxub wkdw wklv";
    map<char, int> counts;

    for (char ch : fileContent)
        ++counts[ch];

    for (char ch = 'a'; ch <= 'z'; ++ch)
        cout << ch << ": " << counts[ch] << '\n';
}

或者要打印所有地图内容(如果您不想为未出现的字母打印 0),您可以使用:

for (auto& item : counts) 
    cout << item.first << ": " << item.second << '\n';

练习让读者在代码中添加以排除空格和数字。提示:查找cctype标头。

于 2017-11-03T03:16:31.213 回答