c++ - 计算文件中的单词
问题描述
我正在尝试计算文件中的记录数量,这是我的代码开始。它在一个 1 参数构造函数中
CountWords(const char* filename) {
ifstream file(filename);
string temp;
while (file >> temp) {
words++;
}
file.close();
name = new string[words];
}
统计完记录数后,设置一个与字数大小相同的新字符串数组。
然而,它似乎并不准确?根据 countwordsfree.com,文本文件有 873335 个单词,但程序显示 901326。这怎么可能?
在这种情况下,' ' 空间是否默认作为分隔符?或者我是否必须手动添加它,如果是这样,如何添加?
解决方案
您不能将分隔符添加到 istream 对象。而且您没有将单词初始化为零。
void CountWords(const char* filename) {
ifstream file(filename);
words = 0;
string temp;
while (file >> temp) {
if(temp == "\n" || temp == "\r" || temp == "\t") continue;
words++;
}
file.close();
name = new string[words];
}
推荐阅读
- javascript - 在反应中选择一个值后如何关闭下拉菜单?
- c# - 在大型 (20 GB) 文本文件中查找对象的属性
- python - Google Protocol Buffers 列表 Python 列表
- react-native - 反应原生如何在文本总和后显示 2 个小数
- node.js - 获取请求适用于邮递员,但适用于浏览器
- node.js - 当主服务器关闭时,MongoDB NodeJS 客户端与副本集的连接不会重新连接
- node.js - 如何使用分子独立运行 docker 图像而不是使用“组合”?
- r - 在小鼠中进行后处理,用另一个变量替换一个变量
- html - 如何将关闭图标添加到 bootstrap 5 移动菜单?
- sql - 在上一行内的相同计算值上创建计算值