Registering Word Count with String Arrays

Hi! I'm having a bit of trouble with one of my coding projects for school!
I need to 1. allow the user to enter a sentence and then 2. count how many words are in the sentence. I'm honestly lost on how to go about doing that will a string array so any advice is much appreciated! Below is how far I have gotten and now I must use another function to tell me how many words are in the string.

void getmessage(string& sentence, int& count)
{

cout << "Please enter your message: ";
getline(cin, sentence);

cout << "The message you entered was: " << endl;

while(sentence[count] != NULL)
{
cout << sentence[count];
count++;
}


}
One way is to use stringstreams. You convert your string into a stream, and then use the >> operator to extract each word, delimited by whitespace.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Example program
#include <iostream>
#include <string>
#include <sstream>

int main()
{
    using namespace std;
    cout << "Enter message: ";
    std::string sentence;
    getline(cin, sentence);
    
    std::istringstream iss(sentence);
    std::string word;
    int count = 0;
    while (iss >> word)
    {
       count++;
       std::cout << "Word " << count << ": " << word << endl;
    }
}


Enter message: She sells seashells by the seashore.
Word 1: She
Word 2: sells
Word 3: seashells
Word 4: by
Word 5: the
Word 6: seashore.
This is a huge life saver! Thank you so much for your help!
Topic archived. No new replies allowed.