[英]C Program isn't printing strings properly
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).该程序的重点是从命令行获取参数(单词)并比较它们以查看哪个是最小的与最大的(AKA 字母顺序)。 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 个指针,然后丢弃结果。 2 places 2个地方
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
.这种代码是不稳定的,因为argv[1]
的字符串长度可能满足/超过数组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]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.