我正在用C语言编写一个子手游戏,据我所知这应该可行。我的程序似乎经历了两次循环,似乎两次出现了问题,两次打印出语句并更改了已设置的布尔值。有人可以帮助我确定为什么会发生这种情况吗?
这是我的程序,后面是示例输出。
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
int main()
{
// setting the word to be guessed and a mutable version of it.
const char secretWord[] = "programming";
char workingString[sizeof(secretWord)];
int guessCount = 6;
// setting the mutable version of the string to be all stars.
for (int i = 0; i<strlen(secretWord); i++){
workingString[i] = '*';
}
printf("Welcome to Hangman!\nTry to guess the word one letter at a time.\n\n");
//infinite loop.
while(1){
bool wrongLetter = true;
bool hasStar = false;
printf("# of misses left: %d\tword: = %s \n", guessCount, workingString);
char letter;
printf("Enter a letter: ");
scanf("%c", &letter);
printf("\n");
// go through the array, see if any characters match.
// replace character if they do, set 'wrong letter' to false so no penalty is applied.
for (int i = 0; i<sizeof(secretWord); i++){
if (letter == secretWord[i]){
workingString[i] = letter;
wrongLetter = false;
}
}
// check to see if the string is solved or not.
for (int i = 0; i<sizeof(workingString); i++){
if(workingString[i] == '*')
hasStar = true;
}
// check boolean to see if a star was found
if (!hasStar){
printf("You won! Game Over!\n");
break;
}
// check boolean to see if a wrong guess was made.
if(wrongLetter)
guessCount--;
// check to see if user lost.
if(guessCount==0){
printf("YOU LOSE! The word is: %s\n",secretWord);
break;
}
}
return 0;
}
这是我运行的示例输出。由于该程序由于某种原因两次进入循环,因此语句加倍。
Welcome to Hangman!
Try to guess the word one letter at a time.
# of misses left: 6 word: = **********
Enter a letter: a
# of misses left: 6 word: = *****a****
Enter a letter:
# of misses left: 5 word: = *****a****
Enter a letter: p
# of misses left: 5 word: = p****a****
Enter a letter:
# of misses left: 4 word: = p****a****
Enter a letter: r
# of misses left: 4 word: = pr**ra****
Enter a letter:
# of misses left: 3 word: = pr**ra****
Enter a letter: o
# of misses left: 3 word: = pro*ra****
Enter a letter:
# of misses left: 2 word: = pro*ra****
Enter a letter: g
# of misses left: 2 word: = progra****g
Enter a letter:
# of misses left: 1 word: = progra****g
Enter a letter: m
# of misses left: 1 word: = programm**g
Enter a letter:
YOU LOSE! The word is: programming
我所做的所有猜测都是正确的,但是程序再次循环并认为错误。