counting word occurrence in a file

I am supposed to count the number of times the word "the" appears in a file. i have to count it case sensitively("THE", "The") and case insensitively("the")

My problem is, with the code below, i get 0 or some huge number(32780) instead of 96 and 72.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
 int WordCount::countWords(string wrd)
{
	string word, x;
	int count , counter = 0;
	while(*(file) >> word)
	{
		
		x = (toupper(word[counter]));
		if( wrd.compare(x) ==0)
		{
			count +=1;
		}
	}
	file->close();	
	return count;
}
		
int WordCount::countWordsCase(string wrd)
{
	string word;
	int count;

	while(*(file) >> word)
	{
		if(word.compare(wrd) == 0)
		{
			count++;
		}
	}

	file->close();	
	return count;
}
In the first function count does not contain number of words because words is not converted to upper case except their first character.
In the second and the first functions count was not initialized.
Last edited on
in both function count is not initialized -> random number -> initialize it with 0

counter will is always 0 (toupper applies on the first letter only)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
size_t WordCount::countWords( const string &wrd )
{
	string word;
	size_t count = 0;

	while ( *file >> word )
	{
		
		for ( char &c : word ) c = toupper( c );
		if ( wrd == word ) ++count;
	}

	file->close();	
	return count;
}
		
size_t WordCount::countWordsCase( const string &wrd )
{
	string word;
	size_t count = 0;

	while ( *file >> word )
	{
		if ( word == wrd ) ++count;
	}

	file->close();	
	return count;
}
Last edited on
closed account (Dy7SLyTq)
maybe im missing something vlad, but a) what happens if he passes "log" to countWords, and word is "LOG" i dont remember "log" == "LOG". im not trying to start an arguement with you. im just trying to understand your code.

and also did you mean size_t on line 17? i googled isize_t and came up with nothing
In line 17 there was a typo that I corrected.
As for the function then I used the same logic as it is in the original post. It is obvious that it is supposed that the argument shall be in uppercase.
closed account (Dy7SLyTq)
ok thanks for clearing that. i tried to figure out how that would work other wise
Of course it would be much better to transform the argument also to upper case. But I did not try to rewrite the function anew.
Topic archived. No new replies allowed.