### 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?

 ``12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455`` ``````#include #include #include 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

 ``123456`` ``````std::istringstream is( s ); std::cout << "Number of words in the sentence is " << std::distance( std::istream_iterator( is ), std::istream_iterator() ) << 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.