【发布时间】:2014-09-26 11:12:22
【问题描述】:
您好,我有这个程序可以逐行读取文本文件,它应该输出每个句子中最长的单词。尽管它在一定程度上起作用,但它会用同样大的单词覆盖最大的单词,这是我不知道如何解决的问题。编辑这个程序时我需要考虑什么?谢谢
//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
编辑:如果有人计划使用此代码,请记住在修复换行符问题时不要忘记空终止符。这是通过设置修复的 sentence[strlen(sentence)-1] = 0 实际上去掉了换行符并将其替换为空终止符。
【问题讨论】:
-
word = (char*)calloc(40, sizeof(char));是内存泄漏,因为在下一行你说word = ...。 -
好吧,我通过使用 calloc 为 word 分配空间,然后我为 char* 指针分配一个值,对吗?怎么会是内存泄漏?
-
不。您分配了一些内存(
word是您指向它的指针)。然后你说word = ...,所以你有很多指向分配内存的指针。如果您不相信我,只需将calloc注释掉,它仍然可以完全一样的工作;-) -
在
calloc()word将指向新创建的内存之后,然后在下一行它指向strok返回的不同内存地址,因此分配的内存丢失了,而且你没有在任何地方删除它 -
假设第一行是
Some line with text.——你希望text.把句点算作长度为5的单词吗?如果没有,您需要在strtok()调用中添加更多分隔符——换行符、制表符、各种标点符号。单引号会使事情变得棘手;doesn't是一两个字吗?He said, 'That is a line!'呢?单引号并不是单词的真正组成部分。你可以在这里做出各种合理的决定,只要你是自洽的,这对你正在进行的练习可能并不重要(但“自洽”是一两个词吗?)。