I wrote a C program that is suppose to be a game called 'knifestonepaper'. In it knife defeats Paper, Stone defeats knife and Paper defeats Stone. I wanted to make it user-friendly by prompting the user to enter y(es) or n(o) at certain points.
However, when I use scanf("%c",choice) to store user's choices the program acts 'funny' or automatically loops but works perfectly when I use getchar(). I would like to know is it so. The game code is below.
The points are:
scanf("%c",&mainexit);
/*getchar();
mainexit=getchar();*/
and
scanf("%c",&exit);
/*getchar();
exit=getchar();*/
The game:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char mainexit;
do
{
int choice;
char exit;
printf("Welcome To StoneKnifePaper!!!!! \n");
a:
printf("Pick One Option.(Enter integers)\n");
b:
printf(" 1.Stone. \n 2.Knife. \n 3.Paper. \n 4.Exit. \n GoodLuck! :) \n");
scanf("%d",&choice);
if(choice <1 || choice>4)
{
printf("Wrong Choice!!! Try Again. \n");
goto b;
}
else if ( choice == 4)
{
c:
printf("Are You Sure You Want To Quit? \n [y/n] \n");
scanf("%c",&exit);
/*getchar();
exit=getchar();*/
if (exit == 'Y' || exit == 'y')
{
return 0;
}
else if (exit == 'N' || exit == 'n')
{
goto a;
}
else if (exit != 'N' || exit!= 'n' || exit != 'Y' || exit != 'y')
{
printf("Wrong Entry. (Please Enter 'y' or 'n') \n");
goto c;
}
}
else if (choice >= 1 && choice <=3)
{
int randomnumber = rand()%3 +1;
if(choice==1 && randomnumber == 2)
{
printf("Congratulations!! Player has Won!! Stone Blunts Knife.");
}
else if(choice==2 && randomnumber == 3)
{
printf("Congratulations!! Player has Won!! Knife Cuts Paper.");
}
else if(choice==3 && randomnumber == 1)
{
printf("Congratulations!! Player has Won!! Paper wraps Stone.");
}
else if(choice==2 && randomnumber == 1)
{
printf("Computer has won!! Stone Blunts Knife.");
}
else if(choice==3 && randomnumber == 2)
{
printf("Computer has won!! Knife Cuts Paper.");
}
else if(choice==1 && randomnumber == 3)
{
printf("Computer has won!! Paper Wraps Stone.");
}
else if(choice == randomnumber)
{
printf("It's a draw!");
}
}
else
{
printf("Wrong Choice!!! Try Again. \n");
goto b;
}
printf("\n Play Game Again? Try Your luck. \n [y/n] ");
scanf("%c",&mainexit);
/*getchar();
mainexit=getchar();*/
}while(mainexit== 'Y'|| 'y');
return 0;
}