C++ Program to print the longest word of the string?
<pre><code>    #include &lt;iostream&gt;
#include &lt;string&gt;

using namespace std;

int main()
{
string s;
getline(cin , s) ; #input of string from user
int counter = 0;
int max_word = -1;
int len = s.length(); #length of string
string max = " ";
string counter_word = " ";

for (int i = 0; i &lt; len; i++)
{
    if(s[i] != ' ')
        {
        counter++;
        }

    if(s[i] == ' ' || i == len - 1)
    {
        if(counter &gt; max_word)
            {
            max_word = counter;
                        //handling end of string.
            if(i == len - 1)
                            max = s.substr(i + 1 - max_word, max_word); #sub string command that prints the longest word
                        else
                max = s.substr(i - max_word, max_word);
                }

    counter = 0;
    }
}
cout &lt;&lt; max_word &lt;&lt; " " &lt;&lt; max &lt;&lt; endl; #output
return 0;
}
</code></pre>

<p>The current output is '4 This' on entering the string "This is cool". 
How do I get it to print '4 This; Cool' ?
On running it in Linux through the terminal, it gives me the error
"  terminate called after throwing an instance of 'std::out_of_range' what(): basic_string::substr Aborted (core dumped)  "</p>