2015-05-09 76 views
0

我正在尝试计算字符串数组中字母的频率,并将频率设置为整个字母表大小的数组。我希望我已经设计出这样的大小写不重要的方式。在此之后,我想将最高频率的字母设置为该字母的'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; 
} 
+0

什么是你的输出或任何错误信息? –

+0

我无法运行它。我的编译器说它已经成功编译,但是在输入文件名后,它永远不会停止运行,屏幕上也不会显示任何内容。我只看到我的内存使用量上升... – shoestringfries

+0

好吧,我得到它正确,执行我们的代码,并且运行良好,请确保您输入的文件名为name.txt,并且它在同一个文件夹中运行.exe你的代码是否有 –

回答

1

问题1:

input.open(fileName.c_str()); 
while (!input.eof()) 

需要进行检查,看是否打开的文件都没有。如果文件没有打开,你永远不会得到一个EOF。

input.open(fileName.c_str()); 
if (input.is_open() 
{ 
    while (!input.eof()) 
    // rest of your code 
} 
else 
{ 
    cout << "Couldn't open file " << fileName << endl; 
} 

但是,这只能绷带问题。对于一个文件来说,还有更多的事情可以发生,而不仅仅是你需要注意的EOF。

问题2:

while (!input.eof()) 
{ 
    string newLine; 
    getline (input, newLine); 
    for (int i = 0; i < newLine.length(); i++) 

所以如果函数getline读取EOF?程序像处理有效行一样处理它,然后测试EOF。再次,一个简单的修复:

string newLine; 
while (getline (input, newLine)) 
{ 
    for (int i = 0; i < newLine.length(); i++) 
    // rest of loop code 
} 

只要行被读取,继续前进。如果没有线路,无论为什么,循环退出。

问题3:

如果没有字母字符,该循环将返回“Z”:

for (int i = 0; i < 26; i++) 
{ 
    if (alpharay[i]>=largest) 
    { 
     largest = alpharay[i]; 
     popular = 'a' + i; 
    } 
} 

简单的解决方案是要运行的循环,因为它是,然后测试最大= = 0并打印一个合适的“找不到字母”消息。

+0

感谢您的详细调试。为什么问题3循环返回z?我特别将它放在主要的isalpha循环中以防止错误计数,请解释一下。 – shoestringfries

+0

如果文件中没有字母,所有的'alpharay [i]'都将是0.最大值被初始化为0.每个'alpharay [i]> =最大'将会是'0> = 0',它总是成功的。循环的最后一次迭代将设置'popular ='a'+ 25'。 ž。 – user4581301