开发者

Need help debugging a simple console game

My while loop inside main is not working properly. the way i got it set up it does not start after enetering y. Can anyone help me with this please

#include <stdio.h>
#pragma warning(disable:4996)
#include <stdlib.h>
#include <time.h>

void play_game();

int main()
{
 char resp;

 printf("Welcome to the game of Guess It!开发者_StackOverflow\n\n");
 printf("I will choose a number between 1 and 100.\n");
 printf("You will try and guess that number.If you guess wrong, I\n");
 printf("will tell you if you guessed too high or too low.\n\n");
 printf("You have six tries to guess the number.\n\n");

 play_game();

 printf("Would you like to play again? (y/n)\n");
 scanf("%c%*c",&resp);

 while((resp=='y') || (resp=='Y'))
 {
  play_game();

  printf("Would you like to play again?\n");
  scanf("%c%*c",&resp);

 }

 printf("Goodbye it was fun.\n");
 printf("Hope to play Guess It with you again soon.\n");

 return 0;
}
void play_game()
{
 int num;
 int guess = 0;
 int count = 1;
 count =1;

 srand((unsigned int)time(NULL));
 num = rand() % 100 +1;

 printf("Ok I am thinking of a number. Try to guess it.\n");
 printf("Your guess?\n");
 scanf("%d",&guess);

 while(guess != num && count != 6)
 {
  if(guess > 100 || guess < 1)
  {
   printf("Illegal guess. Your guess must be between 1 and 100.\n");
   printf("Guess again\n");
   scanf("%d", &guess);
   count ++;
  } 
  else if(guess > num)
   {
    printf("Too High! Guess again\n");
    scanf("%d", &guess);
    count ++;
   }
   else if(guess < num)
   {
    printf("Too Low! Guess again\n");
    scanf("%d", &guess);
    count ++;
   }
 }
  if (guess == num)
  {
   printf("***CORRECT***\n");
  }
  else 
   printf("Too many guesses\n");

   printf("The number is %d\n\n", num);
}


Probably you can add a "%*c" in your scanf inside the play_game function also to drain out the newline character which you may be typing after you enter the number.


Try to change the "%c%*c" to "%c\n" instead.

The scanf() is scanning your keyboard. And i assume you want to stop scanning after enter press. Therefore the newline char "\n", it correspondes to enterpress.

You can also use a do while instead of your while. That way you only have to write the duplicated code once. For example:

 do
 {
  play_game();

  printf("Would you like to play again?\n");
  scanf("%c%*c",&resp);

 } while((resp=='y') || (resp=='Y'))

This way the code inside your du while body is executed before the condition gets checked.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜