The header file conio.h
and its getch()
are not part of standard C and you should probably avoid using them.
See Why is getch not portable? and Why must we refrain from using conio.h? Is it obsolete?.
Your loop seem to go on till the user enters a word of length exactly 4. No need to use a separate variable like finish
for it. Just use a break
statement.
ie, instead of
if (strlen(word) == 4)
{
finish++;
}
do
if (strlen(word) == 4)
{
break;
}
and you can get rid of that finish
variable.
scanf()
expects pointers to buffers where the scanned input need be stored as parameters after the format string. With
scanf("%s", &word);
you are giving pointer to a pointer as word
itself is a pointer since array names in C decay into pointers to their first element. So word
by itself points to the first character stored in the word[]
array.
Use
scanf("%19s", &word);
instead. 19 is the width specifier. 19 was chosen since the size of word
is 20
and we need 1
character space to store the \0
denoting the end of string. This can help avoid buffer overflow.
You may also want to check the return value of scanf()
. It returns the number of successful assigments like
if( scanf("%19s", &word)!=1 ) {
//Something went wrong.
}
See What happens if I use "&" with string in scanf function?.
Usage of fflush()
on stdin
leads to undefined behaviour in C as it is meant to be used only on output streams. See Using fflush(stdin).
strcmp()
just returns a negative number if the first argument is lesser than the second and a positive number if first argument is greater than the other. These numbers could be anything. You need not save the return value of strcmp()
.
So instead of
if (strcmp(word, smallest_word)<smallest)
{
strcpy(smallest_word, word);
smallest = strcmp(word, smallest_word);
}
if (strcmp(word, largest_word) > longest)
{
strcpy(largest_word, word);
longest = strcmp(word, largest_word);
}
do
if (strcmp(word, smallest_word) < 0)
{
strcpy(smallest_word, word);
}
if (strcmp(word, largest_word) > 0)
{
strcpy(largest_word, word);
}
So, you could change the program to
char word[20], smallest_word[20], largest_word[20];
for(int count=0; ; ++count)
{
printf("enter word:");
scanf("%19s", word);
if (count == 0)
{
strcpy(smallest_word, word);
strcpy(largest_word, word);
}
if (strcmp(word, smallest_word) < 0)
{
strcpy(smallest_word, word);
}
if (strcmp(word, largest_word) > 0)
{
strcpy(largest_word, word);
}
if (strlen(word) == 4)
{
break;
}
}
printf("smallest word: %s\n", smallest_word);
printf("largest word: %s\n", largest_word);