It's not entirely clear what you are attempting. However, I understand you want to read a number of lines, and from those lines, determine the longest (stored in max
) and the shortest (stored in min
) and then be able to output the longest and shortest along with the number of characters.
That can be done without much difficulty, but I would suggest more meaningful variable names for the length for the max (say lmax
) and for the min (say lmin
). Those are much more descriptive that i
, j
.
Since you are reading with getchar()
, there is one more (not so uncommon) corner-case you must consider and handle. That being when the final line in the file you are reading from does not end with a '\n'
(called a non-POSIX line end). You can do that by simply checking if characters remain unprocessed after the loop ends.
Putting those pieces together, you could do something like the following:
#include <stdio.h>
#include <string.h>
#define MAXC 100
int main (void)
{
int c;
int i = 0, n, lmin = MAXC, lmax = 0;
char input[MAXC] = "",
max[MAXC] = "",
min[MAXC] = "";
while ((c = getchar()) != EOF) /* read each char until EOF */
{
input[i++] = c; /* store in input, advance counter */
/* (i == maxc - 1) or (c == \n), test max/min */
if (i + 1 == MAXC || c == '\n') {
if (c == '\n')
input[--i] = 0; /* nul-terminate */
else
input[i] = 0;
if ((n = strlen (input)) > lmax) { /* it's a new max */
lmax = n; /* save length */
strcpy (max, input); /* copy input to new max */
}
if (n < lmin) { /* its a new min, handle same way */
lmin = n;
strcpy (min, input);
}
input[0] = 0; /* set input to empty-string */
i = 0; /* zero character index */
}
}
if (i > 0) { /* handle last line w/o POSIX line end */
input[i] = 0; /* nul-terminate, preform same tests */
if ((n = strlen (input)) > lmax) {
lmax = n;
strcpy (max, input);
}
if (n < lmin) {
lmin = n;
strcpy (min, input);
}
}
printf ("longest (%2d-chars) : '%s'\n"
"shortest (%2d-chars) : '%s'\n",
lmax, max, lmin, min);
return 0;
}
Example Input
$ cat dat/sentences.txt
my dog has fleas
poor dog
my cat has none
lucky cat
which animal should I keep?
Example Use/Output
$ ./bin/longshortstr <dat/sentences.txt
longest (27-chars) : 'which animal should I keep?'
shortest ( 8-chars) : 'poor dog'
If this wasn't the output you are looking for, let me know and I'm happy to help further.