I am writing a program that takes multiple words as input and determines which word would come first and last if the words were listed in dictionary order. However my program does not fully work just yet.
Code:
#include <stdio.h>
#include <string.h>
void getword(void);
char str[20];
char smallest[20];
char largest[20];
int main(int argc, char *argv[]) {
while (strlen(str) != 4) {
getword();
if (strcmp(str, smallest) < 0) {
strcpy(smallest, str);
} else
if (strcmp(str, largest) > 0) {
strcpy(largest, str);
}
}
printf("smallest:%s\nlargest:%s\n", smallest,largest);
return 0;
}
void getword(void) {
printf("Enter a word: ");
scanf("%s", str);
}
The user must enter words, I will assume the words are no longer than 20 characters long and if the user enters a 4 letter word then the program will stop.
The problem I have is that the first if
statement (tests for smallest word in dictionary order) does not work. When the program is ran the output looks like this:
Enter a word: dog
Enter a word: zebra
Enter a word: rabbit
Enter a word: catfish
Enter a word: walrus
Enter a word: cat
Enter a word: fish
smallest:
largest:zebra
As you can see the 'smallest' word is not picked up and a simple printf statement in the if statement shows me that my program doesn't even enter the if statement at all, why is this?