这段代码的目的是取一个已经传入程序的文件,生成文件中每个字母的字母频率。在上面的代码中,我删除了标点符号并转换为小写字母。
#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++,非常感谢您更有经验的开发人员的任何建议。谢谢你!