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

Storing and outputting word.length() into an array

本文关键字:输出 数组 存储 word length      更新时间:2023-10-16

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

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

#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(我假设这是垃圾内存)的变化。我真的可以在这个问题上使用stackoverflow的功能,因为我被难住了:/。

编辑:我正在读取的文件是一个"所有"英文单词的列表,以/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++编程)。为了避免这个错误,只要在增加wordlength[len]之前确保len小于array_size,通过将增量包装在if中:

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。关于样式的另一个注意事项:ok使用全局常量,但建议将其命名为ARRAY_SIZE而不是array_size,以便清楚地表明它是一个常量。

同样,正确缩进代码。更好的方法是使用可以自动缩进代码的编辑器。

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

我补充说:

int wordlength[array_size] = {0};

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

Thanks to all that help:)