所以这是我的代码:
#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,如果这有帮助的话。 提前谢谢!
答案 0 :(得分:2)
简单的回答是刷新缓冲区。
stdin缓冲区,从键盘(或管道)获取指令并将其提交给程序的缓冲区偶尔会出现一些字符&#34;卡住&#34;在里面。从未完全提交的垃圾字符,额外的退货等会导致scanf()认为它达到了正确的结果,但实际上并没有。
fflush(stdin);
功能fflush&#34;刷新&#34;一个缓冲区。这样做的效果是消耗来自缓冲区的数据,直到收到的数据是字符“0”和“0”。 (空值)。这意味着它已到达当前缓冲区中的最后一个数据。
在调用scanf()之前调用它意味着当调用scanf()时,你有理由知道程序将在scanf()上阻塞,直到你提交,而不只是从缓冲区消耗一些垃圾。