C - find the longest word in a sentence
Hi I have this program that reads a text file line by line and it should output the longest word in each sentence. While it works to a certain extent, it rewrites the biggest word with the same big word, which I'm not sure how to fix. What do I need to think about when editing this program? Thanks to
//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;
}
My text file that the program accepts contains this
some line with text
another line of words
Jimmy John took the a apple and something reallyreallylongword it was nonsense
and my conclusion is
text
another
reallyreallylongword
but I would like the result to be
some
another
reallyreallylongword
EDIT: If anyone is planning on using this code, remember, when you fix the newline problem, don't forget the null terminator. This is fixed by setting the clause [strlen (clause) -1] = 0, which effectively gets rid of the newline character and replaces it with a null terminator.
source to share
You get each line using
fgets(sentence, 100, file)
The problem is that the new character of the string is stored internally sentence
. For example, the first line "some line with text\n"
that makes the longest word "text\n"
.
To fix this, remove the new line character every time you get sentence
.
source to share