将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(我假设这是垃圾内存)的变化。我真的可以在这个问题上使用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:)
- 使用递归输出数组
- C++ 输出数组中的最高元素
- 空指针(为缺少的输出数组调用的 create() 在 create,文件 /home/m/OpenCV/modules/
- C++ 为什么我会得到垃圾输出数组?
- C 默认如何输出数组
- 使用递归输出数组
- 从 VB6 调用的 C++ DLL 函数中的输出数组参数
- 递归函数,用于输出数组的最小数量
- 如何在 c++ 中水平输出数组
- 冒泡排序未正确排序或输出数组值
- 按相反顺序输出数组的元素
- 制作一个排列函数,输出数组中所有可能的排列
- OpenCV (c++)缝合器不写入输出数组
- 创建一个3x3x3阵列.用0到9之间的随机值填充.输出数组.找出3个最小值和3个最大值的输出
- 实现[B,C]=f(A)语法(函数f作用于具有两个或多个输出数组的数组)
- 双指针输出数组参数异常
- SWIG Python C++输出数组给出'unknown type'错误
- 以 XLL 为单位获取调用方定义的输出数组尺寸
- c++:如何从函数接收可变长度的输出数组
- 未定义的符号 输出数组 opencv fedora.