试图做一个简单的搜索和计数输入字在c++
Trying to do a simple search and count for the input word in C++
这是我到目前为止的代码
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循环将文件指针推进到文件末尾,因此计数算法在文件末尾开始和结束,实际上什么也不做。
相关文章:
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 我正在尝试使用 c++ 编写二叉搜索树,但该程序仅接受 2 个输入并停止
- 用户输入字符串的结构的搜索向量
- 如何在数组中搜索之前已输入的 int 值
- 搜索用户输入的字符串数组
- 如何在 中输入记录的一个字段时搜索记录
- 搜索使用用户输入的数组
- 我试图证明一个给定的树是一个二进制搜索树.我将输入一个二叉树,我只想让函数返回true
- 基于用户输入搜索存储在矢量内的库存
- 在输入流中搜索字符串
- 广度优先搜索输入
- 在 c++ 中搜索文件中的字符串以查找非常大的输入的有效方法
- 需要帮助在填充了用户输入的向量中搜索最小值
- 字符串搜索输入中包含的单词
- 获取用户输入并搜索2D数组
- 从用户输入中搜索两个值-第二个值失败
- 试图做一个简单的搜索和计数输入字在c++
- 如何在C++中使用 cURL 让用户输入 URL 的搜索词
- 我将如何在文本文件中搜索用户输入的每个单词
- c++在二叉搜索树中从文本文件中输入单词