word count func not counting words.

I searched on the forum and really didnt find anything for my specific needs so here goes. This program compiles with no errors but it doesnt count the words in the user entered string. any suggestions?

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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

#include <iostream>		
using namespace std;

// prototype function
void wordCount(char *str);

int main()
{
	// array to hold user input
	const int SIZE = 80;
	char input[SIZE];

	// get string from the user
	cout << "Enter a string and I will ";
	cout << "display the number of words in it.\n";
	cin.getline(input, 80);

	// display wordCounter function.
	wordCount(input);
	return 0;
}


//***************************************************
// this function  accepts a pointer to a C-string
// as an argument and returns the num of words in the 
// string.
//****************************************************
void wordCount(char *str)
{
	int numWords = 0;

	while (*str != 0)
	{
		// skip any leading spaces
		while (*str != 0 && isspace(*str))
			str++;

		if (*str != 0)
			numWords++;

		// skip over the next word
		while (*str != 0 && !isspace(*str))
			str++;
	}
	
}
		

closed account (DSLq5Di1)
You're not doing anything with the result of wordCount()?

1
2
3
4
5
6
int wordCount(char *str) // don't forget to adjust your prototype
{
    ...

    return numWords;
}

cout << wordCount(input);
sloppy9's response is correct or if you want to keep your function as type void use the following.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void wordCount(char *str)
{
	int numWords = 0;

	while (*str != 0)
	{
		// skip any leading spaces
		while (*str != 0 && isspace(*str))
			str++;

		if (*str != 0)
			numWords++;

		// skip over the next word
		while (*str != 0 && !isspace(*str))
			str++;
	}
	cout << "You entered " << numWords << " words."; // displays number of words

}
FWIW, I would recommend sloppy's approach (return the value).

Generally you want to limit what a function does to 1 thing. In this case, your function is called 'wordCount' so it should do 1 thing: count the words.

Outputting the count to the user is a separate job and shouldn't be done by such a function.
Thanks alot guys/gals. Ill give it a try right now.
Topic archived. No new replies allowed.