Generating a dice game - C Programming -


i'm following tutorial on youtube , doing dice generator. print out 3 dice result , sum out dice result. after which, user @ sum, , based on sum, user going guess whether next roll going higher,lower, or same.

below code, suppose, when typed 'yes', should doing code inside if statement. however, went straight else statement. can please tell me what's wrong?

int answer; int guess; int diceroll4 = 0; printf("would guess next dice? y/n \n"); scanf(" %c", &answer);  if (answer == 'yes' ){      printf("what guess?\n");     printf("please key in number \n");     scanf(" %d", &guess);     if (guess > diceroll4 ){         printf(" got wrong, high!");     }     else if (guess < diceroll4){             printf(" got wrong, low!");     }     else {         printf("you got right");     }  } else{     printf("thanks playing"); } 

first of all, answer should array of chars in order hold string. change

int answer; 

to

char answer[10]; //or other reasonable size 

secondly, since want scan string , not character, change

scanf(" %c", &answer); 

to

scanf("%9s", answer); 

the 9 scan maximum of 9 characters (+1 nul-terminator @ end), preventing buffer overflows.
i've removed & %s expects char* while &answer give char(*)[10]. name of array gets converted pointer first element char*, %s expects. above scanf equivalent to

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

thirdly, comparing 2 strings using == compares pointers , not actual content in them. use strcmp string.h instead. returns 0 when both arguments hold same content. change

if (answer == 'yes' ){ 

to

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

double quotes used denote nul-terminated string(char*), strcmp expects, while single quotes, in code, multi-character literal value implementation-defined.


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -