Jack Longen
Jack Longen

Reputation: 61

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

Here is my code this far

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 has loads of words and numbers. I do not quite understand how does istream iterator count words but I got some results with it. The only error I get at the moment is

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

and that occurs in line starting with "int cnt". I've tried for a few hours but I am not that familiar with C++, it seems I'd have to create an extra string or change word string somehow.

I'd appreciate any help!!

Upvotes: 1

Views: 803

Answers (3)

rohitsan
rohitsan

Reputation: 1041

You are getting an output of 0 because of the while loop that tacp asked you to remove. The while loop advances the file pointer to end of file so the count algorithm starts and ends at end of file effectively doing nothing.

Upvotes: 0

taocp
taocp

Reputation: 23624

This line is not correct:

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

should be:

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

Meanwhile, remove the following part:

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

Since otherwise, file will be pointed at end of file when you using the iterator with count algorithm. You should either using loop or iterator, not both at the same time.

Upvotes: 1

rohitsan
rohitsan

Reputation: 1041

The problem is: word(). You are trying to call operator() on an std::string but there is no such member function in std::string.

change your statement to:

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

Upvotes: 0

Related Questions