Here is my code at the moment:
#include <stdio.h>
#include <string.h>
#define WORD_LEN 20
int main(int argc, char *argv[]) {
int i;
char smallest_word[WORD_LEN + 1],
largest_word[WORD_LEN + 1],
current_word[WORD_LEN + 1];
current_word == argv[1];
strcpy(smallest_word, (strcpy(largest_word, current_word)));
for (i=2; i<argc; i++) {
current_word == argv[i];
if (strcmp(current_word, smallest_word) < 0) {
strcpy(smallest_word, current_word);
}
else if (strcmp(current_word, largest_word) > 0) {
strcpy(largest_word, current_word);
}
}
printf("\nSmallest word: %s", smallest_word);
printf("\nLargest word: %s", largest_word);
return 0;
}
The point of this program is to take arguments (words) from the command line and compare them to see which is the smallest vs the largest (AKA alphabetical order). I feel like I have the program down and it should be working, but when I try to run the code, the output is strange squiggly characters instead. If my input was as follows, then the output would be:
Input:
./whatever.exe hello there general kenobi
Output:
Smallest word: ▒
Largest word: ▒
Whereas the correct input and output should be as follows:
Input:
./whatever.exe hello there general kenobi
Output:
Smallest word: general
Largest word: there
I am not sure if this is a type problem, or if I have something completely wrong with my program entirely. I look forward to any and all feedback
Wrong way to assign a string
The below compares 2 pointers and then discards the result. 2 places
current_word == argv[1]; // Not the needed code
current_word == argv[i];
Instead a copy of the string was desired.
strcpy(current_word, argv[1]);
Such code is precarious as the string length of argv[1]
may meet/exceed the size of array current_word
. Better code would test. Example:
if (strlen(argv[1]) >= sizeof current_word)) {
fprintf(stderr, "Too big <%s>\n", argv[1]);
exit(EXIT_FAILURE);
}
strcpy(current_word, argv[1]);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.