I have a program that has to get the longest sentence from a file. To achieve this, I am putting the first sentence in an array and then comparing future sentences to the currently largest sentence's size.
However the act of comparing both array's eludes me. The array's current_sentence and longest_sentence are both 80 characters long, but I wish to know which actually contains the longest sentence (which can be up to 80 characters long).
I have already attempted many different solutions (through google, most of which were stackoverflow results) but every time I make an attempt the returned value is the first sentence in the file, which makes me believe that either the check itself fails entirely, or the length of both array's is returned as 80.
These attempts include (but are not limited to):
if((sizeof(current_sentence) / sizeof(char)) < (sizeof(longest_sentence) / sizeof(char))
if(sizeof(current_sentence) / sizeof(current_sentence[0])) < (sizeof(longest_sentence) / sizeof(longest_sentence[0]))
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *langste_regel(char *);
int main(void) {
/*
* stdout and stderr required for proper output
*/
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stderr, NULL, _IONBF, 0);
char *s = langste_regel("vb1.txt");
if(s != NULL) {
printf("\nde langste regel is: %s\n", s);
free(s);
}
return 0;
}
char *langste_regel(char *filename) {
FILE *file;
file = fopen(filename, "r");
if(file == NULL) {
fprintf(stderr, "Kan bestand niet %s openen", filename);
}
char current_sentence[80];
int len = 2;
char *longest_sentence = (char *)malloc(sizeof(char) * len);
fgets(longest_sentence, 80, file);
while(fgets(current_sentence, 80, file)) {
if(sizeof(current_sentence) < sizeof(longest_sentence)) {
strncpy(longest_sentence, current_sentence, 80);
}
}
fclose(file);
return longest_sentence;
}