Prompt user to enter a sentence
Read this sentence into a string
Pass the string to a function that separates each word
Each word then becomes an element in a vector<string>
The program runs but there is just blank output when I want to write the vector's elements to the screen.
This is the separating function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
vector<string> make_sentence(string s)
{
string test = "";
vector<string> v;
for(int i = 0; i<s.size(); ++i)
{
if(s[i] != ' ')
test += s[i];
elseif(s[i] == ' ')
{
v.push_back(test);
test = "";
}
}
return v;
}
and the simple main()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
int main()
{
cout << "Enter a string: " << endl;
string s;
cin >> s;
vector<string> sentence = make_sentence(s);
for(int i = 0; i < sentence.size(); ++i)
{
cout << sentence[i];
}
return 0;
}
Why does make_sentence() not store anything in the vector? Usually you can declare an empty vector and still use push_back() to add elements to it, what am I doing differently?