Ad

Longest Word In A Given String In C

- 1 answer

The input given is a string (space separated) and the aim is to find the longest string. I have the following code and it crashes for some reason.

The input format is : Good Morning

Expected Output: Morning

#include<stdio.h>
#include<stdlib.h>
#include<limits.h>
#include<string.h>
int main()
{
    char str[1001], temp[1001];
    int maxLen= INT_MIN;
    while(scanf("%s", str)==1)
    {
        //printf("%s\n", str);
        if(strlen(str)>maxLen)
        {
            strcpy(temp, str);
            maxLen = strlen(str);
        }
    }
    printf("%s", temp);
}

I am not able to figure out why this is crashing...! Any help is appreciated!

EDIT: Thanks everyone for helping! I have posted the final working answer below!

Ad

Answer

As highlighted by @mch, strlen(str) returns an unsigned integer. So, I typecasted it to integer. And now it works fine!

#include<stdio.h>
#include<stdlib.h>
#include<limits.h>
#include<string.h>
int main()
{
    char str[1001], temp[1001];
    int maxLen= INT_MIN;
    while(scanf("%s", str)==1)
    {
        //printf("%s\n", str);
        if((int)strlen(str)>maxLen)
        {
            strcpy(temp, str);
            maxLen = strlen(str);
        }
    }
    printf("%s", temp);
    return 0;
}
Ad
source: stackoverflow.com
Ad