Function to find sum of certain word in text file:

Hi everyone, I've written a function that has to receive a word as parameter, and then has to find the amount of times that word (uppercase & lowercase) occurs in a text file:

For example, if the word "the" is sent as a parameter, the total amount of times the words "the" and "THE" occurs in the text file, has to be calculated.

However, my function is not displaying the correct amount, please help me to identify what is wrong with my function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int WordCount :: countWords(string wrd)
{
	int counter=0;
	string temp = "";

	while (getline(*file,temp))
	{  
	  for (int i = 0; i < wrd.length();i++)
	  {
	    if (temp[i]==wrd[i])
	    {
	      counter++;
	    }
	    if (temp[i]==toupper(wrd[i]))
	    {
	      counter++; 
	    }
	  }
	}
	
	return counter;
}
Last edited on
if (temp[i]==wrd[i])You're comparing characterrs, not strings. And that index into wrd doesn't make sense.
Topic archived. No new replies allowed.