I need help with the code. It otherwise works fine. But whenever i enter 'Y' to play the game once again it automatically keeps entering character as input to scanf every time i press enter. So, the program never, ends what to do??

#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>

#define SEED 12345

void play(void);        /*function
						 prototypes*/
int throw_d(void);

int main()
{
  char answer='Y';

  printf("Welcome to the game of craps.\n");
  printf("To throw the dice, press ENTER.\n\n");

  srand(SEED);         //initializing the random number generator//

  /*main loop*/
   while(toupper(answer) != 'N'){
	  play();
      printf("Do you want to play again.(Y/N)");
	  scanf_s("%c", &answer);
	  printf("\n");

    }
   printf("Bye........bye...XOXO");
   getchar();

   return 0;
}
 
 void play(void)
  {
    int score1, score2;
	char dummy;
    
	 printf("Please throw the dice");
	 scanf_s("%c", &dummy);
	 
	 score1 = throw_d();
	 
     printf("\n%2d", score1);
     printf("\n");

	 switch(score1){
		 case 7:
		 case 11:
			 printf("Congratulations!! You WIN on the first throw...:P\n");
			 break;
		 case 2:
		 case 3:
		 case 12:
			 printf("Sorry!!You LOOSE on the first throw....:(\n");
			 break;
		 case 4:     /*Additional throws required*/
		 case 5:
		 case 6:
		 case 8:
		 case 9:
		 case 10:
			 do{
				 printf("Throw the dice again...");
				 scanf_s("%c", &dummy);
				 score2=throw_d();
				 
				 printf("\n%2d\n", score2);
			 }while(score2!=score2&&score2!=7);

			 if(score1==score2)
				 printf("You WIN by matching your first score....:P\n");
			 else
				 printf("You LOOSE by not matching your first score....:(\n");
			 break;
	 }
	  return;
 }
  int throw_d(void)
  {
   float x1, x2;  /*random floating point number between 0-1*/
   int n1, n2;   /*random integers between 1-6*/
   x1 = rand()/32768.0;
   x2 = rand()/32768.0;

   n1 = 1+ int(x1*6);
   n2 = 1+ int(x2*6);

   return(n1+n2);
  }

scanf() leaves the Enter key '\n' in the keyboard buffer, so the next time scanf() is called it will only see '\n'. One solution is to replace scanf() with fgets() which will remove '\n' if there is room in the input buffer.

Something like this:

int main()
{
   char answer[255];
   fgets(answer, sizeof(answer), stdin);
   if( answer[0] == 'y' )
   {
       // blabla
   }
}

Thnx guys. it was really helpfull. The code runs fine now.

This question has already been answered. Start a new discussion instead.