Hi all,
I recently started writing a program that generates a random number, then gives the user four chances to guess the number. Upon either a correct guess, or upon using all four chances, the program is supposed to prompt the user to either play again or quit the program. My problem is in the end of the while loop in the main function. The code is below:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <time.h>
void guess( );
int main( )
{
char again = 'y';
while (again == 'y')
{
printf("\nTry to guess a number between 1 and 100.\n");
guess( );
printf("\n\nWould you like to play again? (y/n): ");
scanf("%c", &again);
printf("%c", again);
fflush(stdin);
}
printf("\n*****Program Terminated*****\n\n");
return (EXIT_SUCCESS);
}
void guess( )
{
int number;
int counter=1;
int random;
srand(time(NULL));
random = 1 + (rand() % 100);
while (counter <= 4)
{
printf("You have four tries to guess the number.\nYour guess: ");
scanf("%d", &number);
fflush(stdin);
if (number == random)
{
printf("\nHooray! You win!");
counter = 5;
}
else if (counter == 4)
{
printf("\nSorry, you lose. The number was %d.", random);
}
else
{
printf("\nSorry, that is incorrect -");
if (number < random)
{
printf(" the number is larger.");
}
else
{
printf(" the number is smaller.");
}
printf("\n\nYou have %d guesses left.", 4 - counter);
}
counter++;
}
}
When I run the program, it prints the statement asking the user whether to try again, but then it doesn't let me input a "y" or "n". Instead, it automatically exits the loop and terminates the program.
Any comments or suggestions would be greatly appreciated. Thanks.
-Sean