gpt4 book ai didi

c - 最后如何完善C语言的hangman循环问题?

转载 作者:行者123 更新时间:2023-11-30 20:14:09 24 4
gpt4 key购买 nike

绞刑吏有问题,请找出来??输入代码时的字母显示“未找到”,并且必须输入相同的字母两次才能接受它?猜出该字母的机会减少了如何解决?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <ctype.h>

#define WORD_COUNT 3
#define MAX_LENGTH 10

typedef char string[MAX_LENGTH];

void main(void) {

string words[WORD_COUNT] = { "bird","fish","lion","ants","bear","deer","fowl" };

char answer[MAX_LENGTH];
char guess;
int count = -0, 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); a biref menu case
switch (choice) {
case 1:
count = 5;
break;
case 2:
count = 2;
break;
case 3:
count = 1;

}

srand(time(NULL));
index = rand() % WORD_COUNT;

strcpy(mysteryWord, words[index]);/*actual comparing */
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 = 0;

for (i = 0; i < strlen(mysteryWord); i++)
{
if (mysteryWord[i] == guess) {
answer[i] = guess;
found = 1;
}
}
if (found == 0) {
printf("Not found!\n");
--count;
}

if (count == 0) {
printf("Game over\n");
printf("The answer is %s.", mysteryWord);
break;
}

else {
what should be here instead of if(answer==mysteryWord) ?
if (strcmp(answer, mysteryWord) == 0)
{
printf("Yes, it's a %s\n", answer);
break; /* or return */
} else
printf("%s", answer);
}
} end of while loop ?

} end of main ?

最佳答案

改变

  scanf("%c\n", &guess);

  scanf(" %c", &guess);

注意%c之前的空格。空格会丢弃所有空格,例如换行符和空格,然后 %c 将扫描下一个非空格字符。

在您的情况下,当您为任何 scanf 输入数据时,您输入数据并按 Enter 键。scanf 读取输入的数据并留下 stdin 中的\n(换行符)。当您使用 %c 扫描字符时,scanf 会读取上一个 scanf 留下的 \n ,从而,不等待输入。

关于c - 最后如何完善C语言的hangman循环问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27648031/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com