I'm following a tutorial on youtube and was doing a dice generator. It basically print out 3 dice result and sum out the dice result. After which, the user will look at the sum, and based on the sum, the user going to guess whether the next roll is going to be higher,lower, or the same.
Below is my code, suppose, when I typed 'yes', it should be doing the code inside the if statement. However, it went straight to the else statement. Can someone please tell me what's wrong?
int answer;
int guess;
int diceRoll4 = 0;
printf("Would you like to guess your next dice? Y/N \n");
scanf(" %c", &answer);
if (answer == 'yes' ){
printf("What is your guess?\n");
printf("please key in your number \n");
scanf(" %d", &guess);
if (guess > diceRoll4 ){
printf(" You got it wrong, too high!");
}
else if (guess < diceRoll4){
printf(" You got it wrong, too low!");
}
else {
printf("You got it right");
}
}
else{
printf("Thanks for playing");
}
First of all,
answer
should be an array ofchar
s in order to hold a string. Changeto
Secondly, since you want to scan a string and not a character, change
to
The 9 will scan a maximum of 9 characters (+1 for the NUL-terminator at the end), thus preventing buffer overflows.
I've removed
&
as%s
expects achar*
while&answer
will give achar(*)[10]
. Name of an array gets converted into a pointer to its first elementchar*
, exactly what%s
expects. The abovescanf
is thus equivalent toThirdly, comparing two strings using
==
compares pointers and not the actual content in them. Usestrcmp
fromstring.h
instead. It returns 0 when both its arguments hold the same content. Changeto
Double quotes are used to denote a NUL-terminated string(
char*
), which is exactly whatstrcmp
expects, while single quotes, as in your code, is a multi-character literal whose value is implementation-defined.