【发布时间】:2015-07-20 02:15:28
【问题描述】:
我正在尝试计算字符串数组中字母的频率,并将频率设置为整个字母表大小的数组。我希望我已经设计了这样的方式,所以大写/小写无关紧要。在此之后,我想将频率最高的字母设置为该字母表的“e”(因为 e 在许多语言中出现的频率最高)并找出最常见的字母和 e 之间的区别。 这在我的心理演练中似乎是有道理的,但我的编译器出于某种原因给了我断点并且根本不允许我检查它,所以我不确定出了什么问题。所以请原谅我没有发布 SSCCE。提前感谢您的帮助!
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int alpharay[26];
for (int i = 0; i < 26; i++)
{
alpharay[i] = 0;
}
ifstream input;
cout << "File name (.txt): ";
string fileName;
cin >> fileName;
input.open(fileName.c_str());
while (!input.eof())
{
string newLine;
getline (input, newLine);
for (int i = 0; i < newLine.length(); i++)
{
if (isalpha(newLine[i]))
{
int index;
if (isupper(newLine[i]))
{
index = newLine[i] - 'A';
alpharay[index]++;
}
else if (islower (newLine[i]))
{
index = newLine[i] - 'a';
alpharay[index]++;
}
}
}
}
//To find the largest value in array
int largest = 0;
char popular;
for (int i = 0; i < 26; i++)
{
if (alpharay[i]>=largest)
{
largest = alpharay[i];
popular = 'a' + i;
}
}
//To find the size of the shift
int shift = popular - 'e';
cout << "Shift size: " << shift << endl;
return 0;
}
【问题讨论】:
-
你的输出是什么?或任何错误信息?
-
我无法运行它。我的编译器说它已经编译成功,但是在输入文件名后它就永远不会停止运行,屏幕上什么也没有出现。我只看到我的内存使用量不断上升......
-
好吧,我说得对,执行了你的代码并且运行良好,确保你输入文件名作为 name.txt 并且它应该在你的代码的 .exe 所在的同一个文件夹中
-
你传入的文件是什么?如果您没有看到输出,它似乎会在那里无限循环。
-
输入名称作为name.txt,它会解决你的问题
标签: c++ arrays loops for-loop ifstream