[英]C Program isn't printing strings properly
這是我目前的代碼:
#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;
}
該程序的重點是從命令行獲取參數(單詞)並比較它們以查看哪個是最小的與最大的(AKA 字母順序)。 我覺得我的程序已經關閉並且它應該可以工作,但是當我嘗試運行代碼時,輸出是奇怪的波浪形字符。 如果我的輸入如下,那么輸出將是:
輸入:
./whatever.exe hello there general kenobi
輸出:
Smallest word: ▒
Largest word: ▒
而正確的輸入和輸出應該如下:
輸入:
./whatever.exe hello there general kenobi
輸出:
Smallest word: general
Largest word: there
我不確定這是否是類型問題,或者我的程序是否完全有問題。 我期待任何和所有反饋
分配字符串的錯誤方法
下面比較 2 個指針,然后丟棄結果。 2個地方
current_word == argv[1]; // Not the needed code
current_word == argv[i];
而是需要字符串的副本。
strcpy(current_word, argv[1]);
這種代碼是不穩定的,因為argv[1]
的字符串長度可能滿足/超過數組current_word
的大小。 更好的代碼會測試。 例子:
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.