将 word.length() 存储并输出到数组中

Storing and outputting word.length() into an array

我已经做了几个小时了,我很难读入我的文本文件,计算每个单词有多少个字母,每个字母的单词数量。

到目前为止,我已经想到了这个:

#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
#include <fstream>

using namespace std;

const int array_size = 29;

int main() {

ifstream inputfile;
string word, word2;
int wordlength[array_size];
int length = 0;

cout << left << setw(10) << "Length: ";
cout << left << setw(10) << "# of words: " << endl;

inputfile.open("C:/EnglishWords.txt");

while (inputfile) {

    inputfile >> word;

    int len = word.length(); 
    wordlength[len]++; //initialized array for '29'

    for (int i = 1; i < 29; i++) {
        cout << left << setw(10) << wordlength[i];
        cout << left << setw(10) << i;
    }
}

getchar();
getchar();

return 0;
}

对于我想要打印的每个实际值,我基本上得到 -8293729 的变体(我假设这是垃圾内存)。我真的可以在这个上使用 Whosebug 的强大功能,因为我被难住了:/。

编辑:我正在阅读的文件是 "all" 个由 /n 分隔的英文单词的列表;

首先,你的wordlentgth数组没有初始化。 在递增之前尝试使用 for 循环将其内容设置为 0。或者,更好的是,使用 memset

int wordlength[array_size];
memset(wordlength, 0, array_size);

编辑:int wordlength[array_size] = {0}; 是这种情况下的方法。例如,当您必须重新设置数组时,memset 很有用。

您需要 #include <cstring> 才能使用它。

其次,如果任何单词大于 array_size,您的程序将因分段错误而崩溃(您应该查找它,这将是您在编程时遇到的最常见错误C/C++)。为了避免此错误,只需确保 len 小于 array_size,然后通过将增量包装在 if:

中来增加 wordlength[len]
int len = word.length(); 
if(len < array_size) {
    wordlength[len]++;
} else {
    cerr << "A word was ignored because it was too long: \"" << word << "\"\n";
}

最后,您应该阅读一些有关命名约定的内容。这确实是一个偏好问题,但只是尽量保持一致(即 wordlength 不遵循与 array_size 相同的约定)。你写的array_size的写法叫做snake-case,我个人很喜欢,但是C语言家族的主流风格是CamelCase。 另外注意一下样式:可以使用全局常量,但是真的建议给它起个名字,这样一目了然是常量:ARRAY_SIZE而不是array_size.

此外,请正确缩进您的代码。更好的是,使用可以自动缩进代码的编辑器。

我只是想澄清一下,我通过初始化数组解决了我的问题。

我补充了:

int wordlength[array_size] = {0};

到我文件的顶部,不再输出转储内存。

感谢所有的帮助:)