gpt4 book ai didi

c - 字母猜谜游戏奇怪的输出

转载 作者:太空宇宙 更新时间:2023-11-04 08:40:03 25 4
gpt4 key购买 nike

这是我的代码:

#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#define MAX_GUESSES 4
int PlayGame(char guess);
int WinOrLose(char userguess, char solution);
int main()
{
FILE* infile;
char correctlet;
int games,
igame,
result;
infile = fopen("inputLet.txt", "r");
printf ("Welcome to the letter guessing game!\n");
printf ("Your job is to guess a random letter.\n");
printf("You can guess each letter a maximum of 4 times,\n");
printf ("and you will get a hint after every guess.\n");
printf ("LET'S DO THIS!\n\n>");
printf ("\nHow many games would you like to play (1-3)?\n>");
scanf ("%d",&games);
for(igame=0;igame<games;igame++)
{
fscanf(infile," %c",&correctlet);
printf("This is game %d\n", igame+1);
result = PlayGame (correctlet);
if (result == 0)
{
printf ("\nCongratulations, you guessed the right letter!\n");
}
else
{
printf ("\nUnfortunately, you did not guess the right letter. Better luck next time!\n");
}
}
return 0;
}
int PlayGame(char solution)
{
int guessnumber,
result;
char userguess;
guessnumber = 0;
while(guessnumber < MAX_GUESSES)
{
printf("Please enter your guess\n>");
scanf("%c", &userguess);
if (sizeof userguess == 0)
{
continue;
}
else if (sizeof userguess >=1)
{
printf ("Your guess was %c\n",userguess);
result = WinOrLose (userguess, solution);
if (result == 0)
{
return 0;
break;
}
else if (result == 1)
{
if (solution < userguess)
{
printf("The correct letter comes before %c alphabetically\n", userguess);
}
else if (solution > userguess)
{
printf("The correct letter comes after %c alphabetically\n", userguess);
}
guessnumber ++;
}
}
}
}
int WinOrLose (char userguess, char solution)
{
if(solution==userguess)
{
return 0;
}
else if (solution != userguess)
{
return 1;
}
}

输出询问游戏的数量,然后它输出请输入您的猜测您的猜测是(空白)正确的字母在后面(空白)请输入您的猜测然后它允许用户输入。那么为什么它在不要求用户输入的情况下进行一次 PlayGame 迭代呢?我已经尝试了所有我能想到的方法,但无法解决问题。如果有帮助,我正在编译 VC++ 2010。提前致谢!

最佳答案

简单的答案是刷新缓冲区。

stdin 缓冲区,从键盘(或管道)获取指令并将其提交给程序的缓冲区偶尔会在其中“卡住”一些字符。从未完全提交的垃圾字符、额外的返回等会导致 scanf() 认为它已到达正确的终点,但实际上并没有。

fflush(stdin);

函数 fflush “刷新”缓冲区。这样做的效果是消耗缓冲区中的数据,直到接收到的数据是字符“\0”(NULL)。这意味着它已到达缓冲区中当前的最后一个数据。

在调用 scanf() 之前调用它意味着当调用 scanf() 时,您有理由知道程序将阻塞 scanf() 直到您提交,而不仅仅是消耗缓冲区中的一些垃圾。

关于c - 字母猜谜游戏奇怪的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24086057/

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