scanf() 将字符添加到字符串
我有这段代码,当我比较它们时,它会不断地将猜测字符串添加到单词字符串中,导致它们永远不会相同。我该如何解决这个问题?
#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;
}```
I have this code and it keeps adding what ever the guesses string is to the wordle string when I compare them, resulting in them to never be the same. How can I fix this?
#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;
}```
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的程序有未定义的行为。你犯了两个错误。
如果您的用户输入 5 个字符,则需要 6 个字符来存储该字符串。该程序将尝试将空终止符写入
wordle[5]
,这不是有效的索引。您的用户可以输入任意数量的字母。您需要确保它们不会溢出您的缓冲区。
查看实际操作
scanf、fscanf、sscanf、scanf_s、fscanf_s、sscanf_s
MSC24-C 。不要使用已弃用或过时的函数
Your program has undefined behavior. You're making two mistakes.
If your user enters 5 characters, it takes 6 characters to store the string. The program would attempt to write a null terminator into
wordle[5]
which is not a valid index.Your user could enter any number of letters. You need to make sure they don't overflow your buffer.
See it in action
scanf, fscanf, sscanf, scanf_s, fscanf_s, sscanf_s
MSC24-C. Do not use deprecated or obsolescent functions
您的单词和猜测字符串太短。您需要为“\0”腾出空间。它们的长度应该是 6 个字节而不是 5 个字节。
Your strings for wordle and guesses are too short. You need to make room for '\0'. They should be 6 bytes long not 5.