I have made a game and this is the last part when a player is required to type yes/no to paly again. But the result of this code is unexpected. Code:
do{
setbuf(stdout, NULL);
printf("\nDo you want to play again(yes/no)");
scanf("%s", &yn);
}while(strcmp(yn, "yes")==0||strcmp(yn, "no")==0);
Result:
Do you want to play again(yes/no) no
Do you want to play again(yes/no) yes
Do you want to play again(yes/no) random
Do you want to play again(yes/no)
Its repeating over and over.
Can you fix this code?
strcmp(yn, "yes")==0||strcmp(yn, "no")==0evaluates to true ifynis "yes" or "no" so that would explain the first two tests. You probably want:It does not explain the 3rd test "sjsbs". This probably means
scanf("%s", &yn);failed. You should check the return value.You did not tell us what
ynis but it should be a array so leave out the '&'. It would be particular bad if it's achar yn(see buffer overflow later).Whenever reading a string with scanf()
**always** specify the maximum field width to avoid buffer overflow. If the input is smaller than what is being read byscanf()then a subsequent call would return that. Consider usingfgets()instead ofscanf(). You may still get partial input but with a sufficiently large buffer it will mostly just work. The other option is discard everything in the input buffer till you hit a newline or EOF (usinggetchar()` for instance).do {and} whileshould be at the same level, and I prefer compact code so more of it fits on the screen t a time (i.e. remove all those blank lines).