I am making a little program that takes as input the answer to the question "Are you an adult?" as a character like that:
bool adult() {
char answer;
do {
printf("Are you an adult? [y/n]\n");
answer = getchar();
} while (!(answer == 'y' || answer == 'n'));
return (answer == 'y');
}
My aim was that the question should repeat itself if the answer is neither y or n. But this seems to have a bug:
When I answer something else (neither y or n), the question gets printed twice:
Are you an adult? u Are you an adult? Are you an adult? ...
Why is this happening? Also, I've tried the same method with scanf instead of getchar but there is the same bug. For this kind of program, should I use scanf or getchar and why?
Thanks!