How can i count the number of words in a string?

I have to make it so it will say this phrase has 2 words or this phrase has 7 words. I'm guessing I might have to use a while statement?

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
51
52
53
54
55
#include <iostream>
#include <string>
#include <conio.h>
using namespace std;

int main()
{
	char response;
	int value = 0;
	char msg1[80] = "";
	char msg2[80] = "";

	do
	{
		cout << "Enter a phrase: ";			//get phrase one
		cin.getline(msg1, 80);

		cout << "\nEnter another phrase: ";	//get phrase two
		cin.getline(msg2, 80);

		cout << "\nPhrase \"" << msg1 << "\" has " << strlen(msg1) << " characters.";		//display amount of characters
		cout << "\n\nPhrase \"" << msg2 << "\" has " << strlen(msg2) << " characters.";

		value = strcmp(msg1, msg2);

		if(value == 0)
			cout << "\n\nIn C++, phrase \"" << msg1 << "\" is equal to the phrase \"" << msg2 << "\"";		//determine which phrase is greater
		else if(value > 0)
			cout << "\n\nIn C++, phrase \"" << msg1 << "\" is greater than the phrase \"" << msg2 << "\"";
		else if (value < 0)
			cout << "\n\nIn C++, phrase \"" << msg2 << "\" is greater than the phrase \"" << msg1 << "\"";
	
		cout << "\n\nPlay again(y/n)? ";
		cin >> response;
		toupper(response);

		while(response != 'Y' || response == 'N')
		{
			if(response == 'N')
			{
				cout << "\n\nprogram ends.";
				break;
			}
			cout << "\nEnter a valid option: ";
			cin >> response;
			toupper(response);
		}	
	}
	while(response == 'Y');

	_getch();
	return 0;
}

Let assume that you have a sentence that is stored in an object of type std::string

std::string s( "This is a sentence" );

then the number of words can be gotten the following way

1
2
3
4
5
6
std::istringstream is( s );

std::cout << "Number of words in the sentence is " 
          << std::distance( std::istream_iterator<std::string>( is ),
                            std::istream_iterator<std::string>() )
          << std:;endl;
Last edited on
I have no idea whats going on in there. Im on my first semester of C++
Well, you can use standard function std::strtok, std::strspn, std::strcspn.
In fact it is enough to use std::strtok to count the number of words.
From what im understanding (and I guess im wrong) was to try this which doesn't work. I'm lost.

 
std::strtok(msg1)
Use a loop and loop through each character then count all spaces and add one to it
You should read the description of the function before to use it.
Topic archived. No new replies allowed.