试图做一个简单的搜索和计数输入字在c++

Trying to do a simple search and count for the input word in C++

本文关键字:搜索 输入 c++ 简单 一个      更新时间:2023-10-16

这是我到目前为止的代码

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;
}

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

问题是:word()。您试图在std::string上调用operator(),但std::string中没有这样的成员函数。

将语句改为:

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

由于tacp要求您删除while循环,因此您将获得0的输出。while循环将文件指针推进到文件末尾,因此计数算法在文件末尾开始和结束,实际上什么也不做。