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:( ?