Search code examples
cwhile-loopcharscanfdo-while

How to prompt the user to loop in C?


I’m new to C and currently doing a Jack ‘N Poy that requires the project to restart when the user prompt it like by answering y. However, I can’t seem to grasp its pattern. Have tried it on C++ and it worked but not on C. Can anyone help? I want the user to have the ability to play again after finishing the game.

Here is the code:

  #include<stdio.h>

  int main (){
  char firstPlayer, secondPlayer, again;
  do{
  printf("Jack 'n Poy)\nEnter Player 1 input: ");
  scanf("%c ", &firstPlayer);
  
  printf("Enter Player 2 input: ");
  scanf("%c", &secondPlayer);
  
  switch (firstPlayer){
      case 'x':
      switch (secondPlayer){
          case 'x':
          printf("Draw");
          break; 
          case 's':
          printf("Player 2 wins");
          break;
          case 'p':
          printf("Player 1 wins");
          
      }
      break;
       case 's':
       switch (secondPlayer){
          case 'x':
          printf("Player 1 wins");
          break;
          case 's':
          printf("Draw");
          break;
          case 'p':
          printf("Player 2 wins");
      }
      break;
       case 'p':
       switch (secondPlayer){
          case 'x':
          printf("Player 2 wins");
          break;
          case 's':
          printf("Player 1 wins");
          break;
          case 'p':
          printf("Draw");
       }
      break;
      default:
      printf("Invalid input");
      
}
      printf("\nPlay again? (y/n)");
      scanf("%c", &again);
}
while (again == 'y');
printf("Thank you for playing");

return 0;
}

Have also tried adding a substitute variable for the y and yes it does loop, but the loop skips the first question. enter image description here

Your help are very much appreciated. Thank you very much!


Solution

  • You need to change the format to:

     scanf(" %c", ...);
    

    in all scanfs. Note the ' ' before %c