Q:

How to implement split function to split words from a line?

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?

A:

You have a typo here:
if (!i)
{
   ret.push_back(s.substr(j, i - j));
}

You are only adding a substring if the end index is 0, but this means you never add a substring to the vector.
Instead, you need to add a substring if the end index is not 0:
if (i)   // if (i != 0)
{
   ret.push_back(s.substr(j, i - j));
}

Here's a demo.

