Start New Discussion within our Software Development Community

Just a simple way to separate the words contained in a sentence. As an option you can store the words in a vector. If you are not familiar with a vector, use an array instead.

// count and display the words in a sentence
// optionally store the words in a vector
// a Dev-C++ tested Console Application by  vegaseat  17mar2005

#include <iostream>
#include <sstream>
#include <string>
#include <vector>  // for the vector option

using namespace std;

int main()
{
  string sentence, word;
  // create a string vector to hold the words
  vector<string> sV;

  cout << "Enter a sentence: ";
  getline(cin, sentence);

  // put the sentence into a stream
  istringstream instr(sentence);

  // the >> operator separates the stream at a whitespace
  while (instr >> word)
  {
    cout << word << endl;
    // optionally store each word in a string vector
    // could use an array, but a vector is easier
    sV.push_back(word);
  }

  // now let's look at the vector
  cout << "You typed " << sV.size() << " words:\n";
  for(int k = 0; k < sV.size(); k++)
  {
    cout << sV[k] << endl;
  }  
  
  cin.sync();  // purge enter
  cin.get();   // console wait
  return 0;
}
The article starter has earned a lot of community kudos, and such articles offer a bounty for quality replies.