到目前为止,这是我的代码
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/