首页 > 解决方案 > 计算文件中的单词

问题描述

我正在尝试计算文件中的记录数量,这是我的代码开始。它在一个 1 参数构造函数中

        CountWords(const char* filename) {
            ifstream file(filename);
            string temp;
            while (file >> temp) {
                words++;
            }
            file.close();
            name = new string[words];
        }

统计完记录数后,设置一个与字数大小相同的新字符串数组。

然而,它似乎并不准确?根据 countwordsfree.com,文本文件有 873335 个单词,但程序显示 901326。这怎么可能?

在这种情况下,' ' 空间是否默认作为分隔符?或者我是否必须手动添加它,如果是这样,如何添加?

标签: c++

解决方案


您不能将分隔符添加到 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];
        }

推荐阅读