1

I want to be able to place each individual word of the string of any size into a vector. This is what I have so far:

vector <string> broken;
while(choice != " "){
    int space = choice.find(" ")-1;
    string word = choice.substr(0,space);
    broken.push_back(word);
    choice = choice.substr(space+1);``
    cout << choice;

}

Any help would be greatly appreciated!

Jive Dadson
  • 16,680
  • 9
  • 52
  • 65
Jonny Yi
  • 13
  • 2
  • 2
    Look into `std::istringstream`. You can use it do do stuff like `while (stream >> word) broken.push_back (word);` Hard to get much easier. – user4581301 May 06 '18 at 02:45
  • 2
    Similar question is answered here https://stackoverflow.com/questions/16029324/c-splitting-a-string-into-an-array Updated it using vector::push_back instead of array. – 273K May 06 '18 at 02:48

2 Answers2

1

The easiest way is to use stringstream, you can insert the multiword string in the stringstream then make a while loop inserting from the stringstream to another string, then you'll have each word separated in each iteration of the loop.

stringstream ss;
ss << choice;
vector <string> broken;

string word;
while(ss >> word){
    broken.push_back(word);
}
Khaled Mohamed
  • 406
  • 5
  • 10
0

One possibility is using an istringstream :

istringstream iss(choice);
vector<string> broken{istream_iterator<string>{iss},
                      istream_iterator<string>{}};

You'll need to #include <sstream> and #include <iterator>.

Sid S
  • 6,037
  • 2
  • 18
  • 24