【发布时间】:2016-08-14 06:37:32
【问题描述】:
我已经在这工作了几个小时,我很难读入我的文本文件,计算每个单词有多少个字母,每个字母的单词数量。
到目前为止,我已经想到了这个:
#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 分隔的“所有”英文单词的列表;
【问题讨论】:
-
除了嵌套的
for循环(哦,那是缺少的}?感谢minimal reproducible example)和检查流中的错误之前提取,你没有' t 向我们展示错误。wordlength可能有未初始化的元素。应该是std::map... -
您好,感谢您的回复。我确实在我的 while 循环末尾添加了“}”。所以这不是问题。通过提供 int main() 部分以便您可以编译它,我对如何向您显示错误感到有点困惑?另外,我是编码新手,我对如何实现地图有点困惑,我查了一下,但还是有点迷茫。再次感谢您的回复!
-
这个
while循环应该是while( inputFile >> word) { ... } -
由于您添加了丢失的
},您的代码在您的问题中没有正确呈现,您能解决它吗? -
我修复了“{”问题
标签: c++ file-io count static-libraries string-length