0

I want to split a std::string sentence into std::string words by storing those words in a vector. Here is my function:

#include <iostream>
#include <string>
#include <vector>

using std::cout; using std::cin; using std::endl; using std::vector; using std::string;

vector<string> split_the_sentence(string sentence){
  string word = "";
  vector<string> words;
  for(char& ch : sentence){
    if(ch == ' '){
      words.push_back(word);
      word = "";
    }
    else{
      word+=ch;
    }
  words.push_back(word); // the last word with the full stop
  }
  return words;
}


int main(){
  string line;
  while(std::getline(cin, line)){
    vector<string> words = split_the_sentence(line);
    for(string& word : words){
        cout << word << endl;
    }
  }
  return 0;
}

When I run the code it gives me a bad_alloc() error. Help:( ?

Esh200111
  • 71
  • 1
  • 8
  • Please share the complete example with function call and sample input included. – w08r Oct 04 '20 at 11:41
  • Yeah I did just now. Thanks. – Esh200111 Oct 04 '20 at 11:43
  • [No repro](http://coliru.stacked-crooked.com/a/3c3b91378d2af585) for the `bad_alloc` exception. I'd recommend you use a `std::stringstream` and a 2nd `getline()` with `' '` as delimiter for the whole line, or just read in using ``std::cin` and `push_back()` the single words directly. – πάντα ῥεῖ Oct 04 '20 at 11:47
  • @πάνταῥεῖ Okay will do that then. Thanks. – Esh200111 Oct 04 '20 at 11:51

0 Answers0