Counting words in a char array

I cant get my program to properly count the words in the string. Any help?

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


//Libraries
#include <iostream>
#include <cstring>

using namespace std;

//Main execution begins here
int main()
{
	//Declare variables
	int const size = 30;
	char string[size];
	int length;
	int wordCount=1;

	cin.getline(string, size);
		length = strlen(string);
		cout << length;
	cout << endl;
	cout << string;
	cout << endl;

	for( int i = 0; i < length; i++){
	 if(string[i] == ' ')
	 
	wordCount ++;
	 else
		 wordCount = 1;

	cout << wordCount;

}

	system("PAUSE");
		return 0;
}

Define word.

What do you expect your program to output if I give you the following strings:

1
2
3
4
"this is a test"
" this one too               "
"                           "
"string"


If we go by the number of spaces it contains (like it seems you're doing), then the results would be (respectively)

1
2
3
4
3
16
27
0
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
#include <iostream>
#include <cstring>
using namespace std;

int main()
{
	int const size = 30;
	char userString[size];
	char tempString[size];
	int wordCount = 0;
	char *point;

	cout << "Please enter a string: ";
	cin.getline(userString, size);
	
	strcpy(tempString, userString);
	
	point = strtok (tempString," ");

	while (point != NULL)
	{
		wordCount++;
		point = strtok (NULL, " ");
	}
	cout << "There are " << wordCount << " Words in the string " << "\"" << userString << "\"" << endl;

	cin.ignore();
	return 0;
}


http://www.cplusplus.com/reference/cstring/strtok/?kw=strtok
Last edited on
Topic archived. No new replies allowed.