我有这段代码,当我比较它们时,它不断将猜测字符串添加到单词字符串中,导致它们永远不一样。我该怎么解决这个问题?
#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 wordn",guess);
scanf("%s",guesses);
value = strcmp(wordle,guesses);
if (value == 0){
printf("you winn");
break;
}
guess = guess - 1;
}
return 0;
}```
您的程序有未定义的行为。你犯了两个错误。
-
如果用户输入5个字符,则需要6个字符来存储字符串。该程序将尝试将空终止符写入不是有效索引的
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%*sn", wordle);
} while(chars_read != 1 && strlen(wordle) != 5);
while (guess != 0){
do {
printf("You have %d tries, please guess the wordn", guess);
chars_read = scanf("%5s%*sn", guesses);
} while(chars_read != 1 && strlen(wordle) != 5);
value = strcmp(wordle, guesses);
if (value == 0){
printf("you winn");
break;
}
guess = guess - 1;
}
return 0;
}
看到它在行动
scanf、fscanf、sscanf、scanf_s、fscanf_s和sscann_s
MSC24-C。不要使用不推荐使用或过时的功能
您的单词和猜测字符串太短。您需要为"\0"腾出空间。它们应该是6字节长,而不是5字节。
char wordle[6];
char guesses[6];