Search code examples
cdice

Generating a dice game - C Programming


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");
}

Solution

  • First of all, answer should be an array of chars in order to hold a string. Change

    int answer;
    

    to

    char answer[10]; //Or any other reasonable size
    

    Secondly, since you want to scan a string and not a character, change

    scanf(" %c", &answer);
    

    to

    scanf("%9s", answer);
    

    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 a char* while &answer will give a char(*)[10]. Name of an array gets converted into a pointer to its first element char*, exactly what %s expects. The above scanf is thus equivalent to

    scanf("%9s", &answer[0]);
    

    Thirdly, comparing two strings using == compares pointers and not the actual content in them. Use strcmp from string.h instead. It returns 0 when both its arguments hold the same content. Change

    if (answer == 'yes' ){
    

    to

    if (strcmp(answer, "yes") == 0){
    

    Double quotes are used to denote a NUL-terminated string(char*), which is exactly what strcmp expects, while single quotes, as in your code, is a multi-character literal whose value is implementation-defined.