请帮助。我花了好几个小时试图找到问题无济于事。它完美地工作,直到我进入while循环,然后它似乎用一个循环延迟处理用户的猜测。
以下是代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <ctype.h>
#define WORD_COUNT 8
#define MAX_LENGTH 10
typedef char string[MAX_LENGTH];
void main(void) {
string words[WORD_COUNT] = { "lion", "tiger", "dog", "cat", "pig", "mouse",
"fish", "b ird" };
char answer[MAX_LENGTH];
char guess;
int count = -5, index, i, found, choice = -7;
char mysteryWord[MAX_LENGTH];
printf("Welcome to Hangman!\n");
printf("\n\nChoose an option\n"
"1) Easy\n"
"2) Moderate\n"
"3) Hard\n"
"Your choice: ");
scanf("%i", &choice);
switch (choice) {
case 1:
count = 5;
break;
case 2:
count = 3;
break;
case 3:
count = 1;
}
srand(time(NULL));
index = rand() % WORD_COUNT;
strcpy(mysteryWord, words[index]);
for (i = 0; i < strlen(mysteryWord); i = i + 1)
{
answer[i] = '-';
}
answer[i] = '\0';
printf("%s \n", answer);
while (1 > 0) {
printf("\n %i guess(es) left\n", count);
printf("Guess a letter:");
scanf("%c\n", &guess);
guess = tolower(guess);
/* found is a "flag" variable. When found = 0 (false) we */
/* haven't found a match, and later, if we find a match, */
/* change found = 1; (true) */
found = 0;
for (i = 0; i < strlen(mysteryWord); ++i) /*or i++ */
{
if (mysteryWord[i] == guess) {
answer[i] = guess;
found = 1;
}
}
if (found == 0) {
printf("Not found!\n");
--count;
} /* or --count or count=count-1 */
if (count == 0) {
printf("Sorry, game over.\n");
printf("The answer is %s.", mysteryWord);
break; /* or return;? */
}
else {
/* try instead if(answer==mysteryWord) */
if (strcmp(answer, mysteryWord) == 0)
{
printf("Yes, it's a %s\n"
"Congratulations!\n", answer);
break; /* or return */
} else
printf("%s", answer);
}
} /* end of while loop */
} /* end of main */
这是一个在linux终端中运行的示例。我相信的问题在于,在用户输入字母后,字母猜测是如何处理的。
欢迎来到Hangman!
选择一个选项 1)容易 2)中等 3)硬
剩下4个猜测 猜一封信:c
离开3个猜测 猜一封信:d
2猜猜了 猜一封信:o D-- 剩下2个猜测 猜一封信:g 做- 剩下2个猜测 猜一封信:g 是的,它是一只狗 恭喜!
答案 0 :(得分:0)
执行scanf("%i", &choice);
语句时,它会将用户输入的整数放入int
变量choice
。但是,它还会在输入缓冲区中保留换行符,从而导致用户输入被抛弃。执行scanf("%c\n", &guess);
语句时,输入的下一个字符将放在输入缓冲区中,但%c
只会导致从缓冲区中读取一个字符(换行符),而字符则是用户输入仍然在缓冲区上。因为在格式字符串中的%c之后有一个换行符,所以后面的换行符将被丢弃(因为它匹配下一个换行符)。在随后的迭代中,然后读取仍在缓冲区上的前一个字符。
推荐的解决方案是在%c
之前插入一个空格,如下所示:scanf(" %c", &guess)
。当执行scanf时,单个空格将使它忽略所有其他空白字符,直到第一个非空白字符,在这种情况下意味着仍然在缓冲区上的换行符将被读取并被忽略。