C - 查找句子中最长的单词

use*_*266 3 c text input

嗨,我有这个程序,逐行读取文本文件,它应该输出每个句子中最长的单词.虽然它在某种程度上起作用,但它用一个同样大的词覆盖了最大的单词,这是我不确定如何解决的问题.编辑此程序时需要考虑什么?谢谢

//Program Written and Designed by R.Sharpe
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include "memwatch.h"

int main(int argc, char** argv)
{
    FILE* file;
    file = fopen(argv[1], "r");
    char* sentence = (char*)malloc(100*sizeof(char));
    while(fgets(sentence, 100, file) != NULL)
    {
        char* word;
        int maxLength = 0;
        char* maxWord;
        maxWord = (char*)calloc(40, sizeof(char));
        word = (char*)calloc(40, sizeof(char));
        word = strtok(sentence, " ");
        while(word != NULL)
        {
            //printf("%s\n", word);
            if(strlen(word) > maxLength)
            {
                maxLength = strlen(word);
                strcpy(maxWord, word);
            }
            word = strtok(NULL, " ");
        }
        printf("%s\n", maxWord);
        maxLength = 0; //reset for next sentence;
    }

    return 0; 
}
Run Code Online (Sandbox Code Playgroud)

我接受程序的文本文件包含这个

some line with text 
another line of words 
Jimmy John took the a apple and something reallyreallylongword it was nonsense
Run Code Online (Sandbox Code Playgroud)

我的输出就是这个

text

another
reallyreallylongword
Run Code Online (Sandbox Code Playgroud)

但我想输出

some
another
reallyreallylongword
Run Code Online (Sandbox Code Playgroud)

编辑:如果有人计划使用此代码,请记住修复换行符问题时不要忘记空终止符.这是通过设置句子[strlen(sentence)-1] = 0来解决的,它实际上取消了换行符并用null终止替换它.

Yu *_*Hao 5

你通过使用获得每一行

fgets(sentence, 100, file)
Run Code Online (Sandbox Code Playgroud)

问题是,新行字符存储在里面sentence.例如,第一行是"some line with text\n",这是最长的单词"text\n".

要解决此问题,请在每次获取时删除新行字符sentence.

  • 或者使分隔符列表包含换行符(也可能是选项卡,也可能是其他字符). (2认同)