Kana_chan Kana_chan - 2 months ago 11
C++ Question

C++ Program to print the longest word of the string?

#include <iostream>
#include <string>

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 < len; i++)
{
if(s[i] != ' ')
{
counter++;
}

if(s[i] == ' ' || i == len - 1)
{
if(counter > 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 << max_word << " " << max << endl; #output
return 0;
}


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) "

Answer

If I have understood you correctly then you mean the following

#include <iostream>
#include <sstream>
#include <string>

int main()
{
    std::string s;

    std::getline( std::cin, s );

    std::string::size_type max_size;
    std::string max_word;
    std::string word;

    std::istringstream is( s );
    max_size = 0;
    while ( is >> word )
    {
        if ( max_size < word.size() ) 
        { 
            max_size = word.size();
            max_word = word;
        }           
        else if ( max_size == word.size() ) 
        { 
            max_word += "; ";
            max_word += word;
        }            
    }

    std::cout << max_size << ' ' << max_word << std::endl;    
}    

If to enter string

This is cool

then the output will be

4 This; cool
Comments