C:打印字符串中最长的单词及其长度

时间:2016-11-27 17:07:40

标签: c

我从C语言开始,我正在通过一个自动检查我编写的代码的平台来学习它(例如,它给了我一些任务,在上传代码之后它检查我写的是否给出了有意义的结果)。

到目前为止,一切工作都很顺利,但是我遇到了一个问题,在我看来我已经解决了,但是在上传代码并运行它之后,发生了一个我坦率地不理解的错误。 / p>

任务:打印句子中最长的单词及其长度。

我的尝试:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char str[80], word[80];
    fgets(str, 80, stdin);

    char *token;

    //tokenizing array str
    token = strtok(str, " ");


    while( token != NULL )
    {
        if(strlen(word) < strlen(token) )
        {
            strcpy(word, token);
        }

        token = strtok(NULL, " ");

    }

    printf("%s %d", word, strlen(word));




    return 0;

}

例如,如果写一个

hello my name is jacksparrowjunior goodbye

一个得到

jacksparrowjunior 17

错误是这样的:

TEST
PASSED
==20760== Conditional jump or move depends on uninitialised value(s)
==20760==    at 0x4006B9: main (004799.c:18)
==20760==  Uninitialised value was created by a stack allocation
==20760==    at 0x400660: main (004799.c:6)
==20760== 
==20760== Conditional jump or move depends on uninitialised value(s)
==20760==    at 0x4006E5: main (004799.c:18)
==20760==  Uninitialised value was created by a stack allocation
==20760==    at 0x400660: main (004799.c:6)
==20760== 

我注意到的另一件事是,如果我改变

char str[80], word[80];
        fgets(str, 80, stdin);

char str[1000], word[1000];
        fgets(str,1000, stdin);

我在计算机上运行程序后出错。

2 个答案:

答案 0 :(得分:2)

根据给定的数据而不进行测试,我猜您应该将str和word初始化为“”

[...]
char str[80] = "";
char word[80] = "";
fgets(str, 80, stdin);
[...]

答案 1 :(得分:0)

错误消息既有用又有神秘感。请注意对条件和未初始化的引用。因此,您应该查看代码中的条件(“if tests”)。

错误中的下一行给出了线索​​的位置:第18行和第6行。

相关问题