Dremendo Tag Line

Input a sentence and print the longest word in C++

String Methods - Question 8

In this question, we will see how to to input a sentence and print the longest word in C++ programming. To know more about string methods click on the string methods lesson.

Q8) Write a program in C++ to input a sentence and print the longest word.

Program

#include <iostream>
#include <conio.h>
#include <string.h>
#include <stdio.h>

using namespace std;

int main()
{
    char s[100],w[50],lw[50];
    int i,p;

    cout<<"Enter a sentence\n";
    gets(s);

    for(i=0; i<strlen(s); i++)
    {
        if(s[i]!=' ')
        {
            // store the characters in array w until we find a space
            w[p]=s[i];
            p++;
        }
        else
        {
            // terminate the word by a null character
            w[p]='\0';

            // check if word length is greater than longest word (lw)
            if(strlen(w)>strlen(lw))
            {
                strcpy(lw,w);
            }
            p=0;
        }
    }
    cout<<"Longest word = "<<lw;
    return 0;
}

Output

Enter a sentence
I am learning to code in C++
Longest word = learning
video-poster