I would like to implement a function, that takes string as a line of input (via getline()) and separate (split) words in a vector. I have tried this:
vector<string> split(const string &s)
{
vector<string> ret;
int j = 0, i = 0; // j=="start word boundary", i=="end word boundary"
while (i != s.size())
{
//get words
while (i != s.size() && !isspace(s[i]))
{
i++;
}
//at least one word found (so the 'i' index is not at the beginning of string)
if (!i)
{
ret.push_back(s.substr(j, i - j));
}
//now look for blanks
j = i;
//ignore blanks
while (j != s.size() && isspace(s[j]))
{
j++;
}
//get position for next words back
i = j;
}
return ret;
}
And then tried to see the results:
int main()
{
string tmp;
while (getline(cin, tmp))
{
vector<string> vec = split(tmp);
for (string s : vec)
{
cout << s << endl;
}
}
}
But cannot see anything. Why?