简体   繁体   English

C 中给定字符串中的最长单词

[英]Longest word in a given string in C

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预计 Output:上午

#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!我已经在下面发布了最终的工作答案!

The problem is in the line if(strlen(str)>maxLen) :问题出在if(strlen(str)>maxLen)行中:

strlen(str) returns a size_t , an unsigned integer. strlen(str)返回一个size_t ,一个无符号 integer。 When you compare an int and a size_t , the int gets converted to size_t , resulting in a very big number.当您比较intsize_t时, int会转换为size_t ,从而产生一个非常大的数字。

So the comparison is always false.所以比较总是错误的。

Then you try to print the uninitialized buffer temp .然后您尝试打印未初始化的缓冲区temp

Change int maxLen= INT_MIN;改变int maxLen= INT_MIN; to size_t maxLen = 0;size_t maxLen = 0;

As highlighted by @mch, strlen(str) returns an unsigned integer.正如@mch 强调的那样,strlen(str) 返回一个无符号的 integer。 So, I typecasted it to integer.因此,我将其类型转换为 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM