Extract words from string C++ program

Extract words from string  C++ – This program example will extract every words including special characters from the string that contains spaces or multiple spaces etc. using C++ istringstream class.

Assign input string to istringstream object and within a loop extract each word . for example, if the string is “hello world” then hello and world will be extracted and it can be stored in a data structure or process it. See word frequency count C++ program , where each word has been extracted and processed.


/*
* C++ program examples to extract each
words from a string
*/

#include<iostream>
using namespace std;
//include it for istringstream
#include<sstream>

int main(){
      string inputString;
      cout<<"Enter String:"<<endl;
    getline(cin,inputString);

      //Crete object of istringstream and
      //initialize assign input string
    istringstream iss(inputString);

    string word;
      //Extract each words only..no spaces.
      //This way it can handle any
      //special characters.

    while(iss >> word) {  
            //Display words
            cout<<word.c_str()<<endl;  
    }

      return 0;

}

Output:

Enter String:
hello world !!!
Extracted words:
hello
world
!!!

Related Posts