Trim white space from string
Your current implementation you will lose all but the first word:

std::string str("this is a sentence");
std::string t  = trim(str);

std::cout &lt;&lt; t &lt;&lt; "\n" 

// Output
this


If that is your intention then there is an easier way of doing that:

std::string trim(std::string const&amp; str)
{
    std::string word;
    std::stringstream stream(str)
    stream &gt;&gt; word;

    return word;
}


If you want to trim space of the ends on the string, then I would use the string search functions [coliru demo]:

std::string trim(std::string const&amp; str)
{
    if(str.empty())
        return str;

    std::size_t firstScan = str.find_first_not_of(' ');
    std::size_t first     = firstScan == std::string::npos ? str.length() : firstScan;
    std::size_t last      = str.find_last_not_of(' ');
    return str.substr(first, last-first+1);
}


Here is the string documentation. Boost also has some extra libraries on the subject.