Words in a Sentence

vegaseat 0 Tallied Votes 188 Views Share

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;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.