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

时间:2014-08-04 02:03:55

标签: 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; 
}

程序接受的我的文本文件包含此

some line with text 
another line of words 
Jimmy John took the a apple and something reallyreallylongword it was nonsense

我的输出就是这个

text

another
reallyreallylongword

但我希望输出为

some
another
reallyreallylongword

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

1 个答案:

答案 0 :(得分:5)

您可以使用

获取每一行
fgets(sentence, 100, file)

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

要解决此问题,请在每次获得sentence时删除换行符。