Hangman游戏字母更改顺序的问题,或者解决方案更改为只有一个字母



我正在尝试制作一个刽子手游戏,一切看起来都很好,直到游戏结束时,有时游戏会说解决方案只有一个字符,或者如果我猜是一个字母,他们会开始向右改变位置。我把代码留在这里,我希望有人能帮我找到我的错误,谢谢!

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#define VOCABULARY_SIZE 8
#define MAX_STRING 32
#define MAX_GUESS 6
int random_number(int a, int b)
{
return a + rand() % (b - a + 1);
}
int main()
{
//random word selsection
srand((unsigned)time(NULL));
const char VOCABULARY[VOCABULARY_SIZE][MAX_STRING] = {"vehicle", "building", "shirt", "pencil", "batman", "dromedary", "peach", "hangman"};
char word[MAX_STRING];
int i;
i = random_number(0, VOCABULARY_SIZE - 1);
strcpy(word, VOCABULARY[i]);
//user word
int guesses = 0, length = strlen(word);
char letters[MAX_GUESS];
char input[MAX_STRING];
char temp_char;
char temp_input[MAX_STRING];
do
{
printf("nYour entered letters are: ");
printf("%s", letters);
printf("nYour letters found are: ");
for (int j = 0; j < length; j++)
{
if (word[j] == input[j])
{
printf("%c", word[j]);
}
else
{
printf("_");
}
}
printf("n%d-letter word. %d out of %d failures. Enter a letter: ", length, guesses, MAX_GUESS);
scanf(" %c", &temp_char);
letters[guesses] = temp_char;
letters[guesses+1] = '';
for (int j = 0; j < length; j++)
{
if (word[j] == temp_char)
{
input[j] = word[j];
}
}
guesses++;
printf("nWhat is the word to guess? ");
scanf(" %s", temp_input);
} while ((strcmp(input, word) != 0 || strcmp(temp_input, word) != 0) && guesses <= MAX_GUESS);
if (strcmp(input, word) == 0 || strcmp(temp_input, word) == 0)
{
printf("nCongratulations, the word was %s!", word);
}
else if (guesses > MAX_GUESS)
{
printf("nBetter luck next time... The word was %s", word);
}
}

您的letters数组有一个条目太小,无法容纳您在此行中应用的终止nul字符:

letters[guesses+1] = '';

由于guesses从零开始,并且您的循环测试它是否为<= MAX_GUESS,因此您也有一个off-by-one错误。

这两个错误加在一起意味着letters数组太小了两个字节。很可能它溢出到你的word数组中,当你去打印它时,留下最后的猜测和终止nul。

相关内容

最新更新