[英]scanf() adds character to string
我有這段代碼,當我比較它們時,它會不斷地將猜測字符串添加到 wordle 字符串中,導致它們永遠不會相同。 我怎樣才能解決這個問題?
#include <string.h>
int main() {
char wordle[5];
char guesses[5];
int guess = 5;
int value;
printf("Please input a secret 5 letter word:\n");
scanf("%s",wordle);
while (guess != 0){
printf("You have %d tries, please guess the word\n",guess);
scanf("%s",guesses);
value = strcmp(wordle,guesses);
if (value == 0){
printf("you win\n");
break;
}
guess = guess - 1;
}
return 0;
}```
您的程序有未定義的行為。 你犯了兩個錯誤。
如果您的用戶輸入 5 個字符,則需要 6 個字符來存儲該字符串。 該程序將嘗試將 null 終止符寫入wordle[5]
,這不是有效索引。
您的用戶可以輸入任意數量的字母。 您需要確保它們不會溢出您的緩沖區。
#include <stdio.h>
#include <string.h>
int main() {
char wordle[6];
char guesses[6];
int guess = 5;
int value;
int chars_read;
do {
printf("Please input a secret 5 letter word:\n");
chars_read = scanf("%5s%*s\n", wordle);
} while(chars_read != 1 && strlen(wordle) != 5);
while (guess != 0){
do {
printf("You have %d tries, please guess the word\n", guess);
chars_read = scanf("%5s%*s\n", guesses);
} while(chars_read != 1 && strlen(wordle) != 5);
value = strcmp(wordle, guesses);
if (value == 0){
printf("you win\n");
break;
}
guess = guess - 1;
}
return 0;
}
你的 wordle 和 guesses 字符串太短了。 您需要為“\0”騰出空間。 它們的長度應該是 6 個字節而不是 5 個。
char wordle[6];
char guesses[6];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.