using strlen and finding shortest and longest words
program is to let user input series of words and when user inputs word of length 4 characters, it stops.
It should sort the words alphabetically, so if a group of same-length words is longest/shortest, it outputs longest as last alphabetically, shortest as first alphabetically.
My code is not pulling the longest word correctly.
What is the problem here????
Code:
#include <stdio.h>
#include <string.h>
#define LENGTH 20
int read_line(char str[], int n);
main()
{
char largest[LENGTH];
char smallest[LENGTH]; /* is the size of array okay */
char input[LENGTH];
int len;
printf("Enter word: ");
read_line(input, LENGTH);
len = strlen(input);
strcpy(smallest, input);
strcpy(largest, input);
if (len == 4){
printf("\n\nTime to quit\n\n");
}
for ( ; ; ) {
printf("Enter word: ");
read_line(input, LENGTH);
len = strlen(input); /* where do I use 'len' to find */
/* shortest and longest */
/* input and print those out ?? */
if (strcmp(input, smallest) < 0) /* is this correct code for */
strcpy(smallest, input); /* sorting alphabetically */
else if (strcmp(input, largest) > 0)
strcpy(largest, input);
if (len == 4) break; /* is this necessary operation */
}
printf("\n\n\nYou input four-letter word\n);
printf("So time to quit.\n\n");
printf("Smallest word: %s\n", smallest);
printf("Largest word: %s\n", largest);
return 0;
}
int read_line(char str[], int n)
{
char ch;
int i = 0;
while ((ch = getchar()) != '\n')
if (i < n)
str[i++] = ch;
str[i] = '\0';
return i;
}
not using fgets or stdin yet in class
thanks Sebastiani,
but I got it working.
I haven't learned yet some of the functions you suggest
but will keep in mind later when I do, to see how it affects
input and output (I/O)
later !!!