gpt4 book ai didi

c - 为什么这个 C 循环会跳过第一次输入字母的尝试?

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

这是我为类制作的程序。它应该从文件中读取一个字母,然后在游戏中用户尝试猜测这个字母。对于每一次错误的尝试,程序都会告诉您实际字母是在字母表中您猜测的之前还是之后。

由于某种原因,当我运行它时,循环跳过了 getLetter 函数中的第一次尝试,并且不允许您输入字母。这是为什么?

#include <stdio.h>
#include <ctype.h>
#define MaxGuesses 5

void instructions();
int playGuess (char solution);
char getLetter ();
int compareLetters (char guess, char solution);

int main()
{

int numGames;
int i;
char solution;
char guess;
int result;

FILE *inFile;

inFile=fopen("inputLet.txt","r");

instructions();
scanf("%d", &numGames);

for(i=1; i<=numGames; i++)
{
printf ("\nThis is game %d\n", i);
fscanf(inFile, " %c", &solution);
result = playGuess(solution);

if (result == 1)
printf("You've WON!\n");
else
printf("You've LOST :(\n");

}

//close file
fclose(inFile);
return 0;
}

void instructions ()
{
printf ("This game consists of guessing letters.\nThe user will have up to 5 chances of guessing correctly,\nupon every failed attempt,\na hint will be provided regarding alphabetical position.\n\nEnter the number of games you wish to play (max 4): ");
}

char getLetter()
{
char userGuess;
printf("\nPlease enter your guess: ");
scanf("%c", &userGuess);
userGuess = tolower(userGuess);
return userGuess;
}

int compareLetters(char guess, char solution)
{
if (guess == solution)
return 1;
else if (guess < solution)
{
printf("\nThe letter that you are trying to guess comes before %c", guess);
return 0;
}
else if (guess > solution)
{
printf("\nThe letter that you are trying to guess comes after %c", guess);
return 0;
}
}

int playGuess (char solution)
{
int numGuesses = 0;
int winOrLose = 0;
char guess;
while(numGuesses < MaxGuesses && winOrLose == 0)
{
guess = getLetter();
winOrLose = compareLetters(guess, solution);
numGuesses++;
}

return winOrLose;
}

最佳答案

它可能正在消耗输入缓冲区中剩余的字符(可能是换行符或其他空白字符)。您可以尝试将格式字符串从 "%c" 更改为 "%c" ,就像您在其他地方所做的那样,这将在尝试之前跳过缓冲区中的所有空白字符读取一个字符。

关于c - 为什么这个 C 循环会跳过第一次输入字母的尝试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17119564/

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