これは私がクラスのために作っているプログラムです。ファイルから文字を読み取り、ゲーム内でユーザーが文字を推測することを想定しています。間違えるたびに、プログラムは実際の文字がアルファベットの推測の前後に来るかどうかを教えてくれます。
何らかの理由で実行すると、ループは 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;
}