c++ - 尝试对 C++ 中的输入词进行简单搜索和计数

标签 c++ text count line word

到目前为止,这是我的代码

int main()
{
string word;
int wordcount = 0;
cout << "Enter a word to be counted in a file: ";
cin >> word;
string s;
ifstream file ("Names.txt");
while (file >> s)
        {
            if(s == word)
            ++ wordcount;
        }
int cnt = count( istream_iterator<string>(file), istream_iterator<string>(), word());
cout << cnt << endl;
}

File Names.txt 包含大量单词和数字。我不太明白 istream 迭代器是如何计算单词的,但我得到了一些结果。我现在唯一的错误是

in function int main 
error: no match for call to `(std::string) ()'

这发生在以“int cnt”开头的行中。我已经尝试了几个小时,但我对 C++ 不太熟悉,看来我必须创建一个额外的字符串或以某种方式更改字符串。

如果有任何帮助,我将不胜感激!

最佳答案

这一行不正确:

 int cnt = count( istream_iterator<string>(infile), 
            istream_iterator<string>(), word());
                                          //^^^^^Error

应该是:

int cnt = count( istream_iterator<string>(infile), 
                istream_iterator<string>(), word);

同时,删除以下部分:

while (infile >> s)
{
    if(s == word)
    ++ wordcount;
}

否则,当您使用带计数算法的迭代器时,file 将指向文件末尾。您应该使用循环或迭代器,而不是同时使用两者。

关于c++ - 尝试对 C++ 中的输入词进行简单搜索和计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15863599/

相关文章:

c++ - 使用新的 C++11 语法的 auto 函数声明,但有 auto& 而没有 ->

C++引用与for循环内变量的指针?

text - 如何在 Golang 中创建固定长度的文本文件?

r - 计算未出现较早且未出现在最后一组中的新值

mysql - 对同一列进行 COUNT 两次

c++ - const typedef 之间的区别

c++ - 从标准输入 C++ 读取数百万整数的最快方法?

iphone - 如何测试 UITextField 是否为零?

regex - 如何通过从结果中排除标签来捕获 <TAGs> 中的文本?

mysql - 表的两列和另一表的一列的计数