0

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!

  • 1
    "It doesn't work" is not a technical description of a problem. [ask] – Rob Jan 05 '23 at 09:33
  • 1
    Remove the spaces after ```%c```, add the spaces before ```%c```. And it's a very poor SO etiquette to edit the question after it has received answers/comments. It invalidates them. – Harith Jan 05 '23 at 09:51
  • Does this answer your question? [Read two characters consecutively using scanf() in C](https://stackoverflow.com/questions/24099976/read-two-characters-consecutively-using-scanf-in-c) – chilli10 Jan 08 '23 at 14:21

2 Answers2

0

Your again is a string. You can use strcmp(expectedString,inputString) as the condition at while. You will need to include the string.h header file to be able to do this.

Alternatively, change again to char type, i.e. char again;

And then use %c in the last scanf, i.e. scanf("%c", &again);. You may face skipped character scenario if spaces or newlines are entered. In that case, refer to this answer for guidance.

chilli10
  • 54
  • 1
  • 9
0

You need to change the format to:

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

in all scanfs. Note the ' ' before %c

0___________
  • 60,014
  • 4
  • 34
  • 74