James up James up - 23 days ago 8
C Question

Comparing multiple characters in C

I am making a stone knife paper game.(Rock Paper Scissors) In this assignment we have been asked to use numbers for comparison purposes. Hence the need for converting users input 'S' or 'K' or 'P' to 0 , 1 ,2 repectively.I have run into trouble using the strcmp funtion which doesn't seem to work due to my limited understanding of pointers and characters.

int comp_number,user_number;
char user_guess[1], computer_guess[1];
printf("Please enter S (for stone) or K (for Knife) or P (for Paper).\n");

scanf("%c",&user_guess);

comp_number = rand() % 3;

/*
o = stone
1 = kinfe
2 = paper
*/


if(strcmp(user_guess,"S")==0 || strcmp(user_guess,"s")==0){

user_number=0;

}else if(strcmp(user_guess,"K")==0 || strcmp(user_guess,"k")==0){

user_number=1;

}else{

user_number=2;
}

Ben Ben
Answer

An easier way to do the reading and logic (that looks better) is to scan to a char then do a switch statement:

scanf("%c",&user_guess);

switch (user_guess) {
    case 'S':
    case 's':
        user_number=0;
        break;
    case 'K':
    case 'k':
        user_number=1;
        break;
    case 'P':
    case 'p':
        user_number=2;
        break;
    default:
        // You can even do some error handling in here!
}