How should I do to be able to ask a yes or no question in C
There are 5 input sets to distinguish:
"Y\n" or something similar: "y\n", "Yes\n", "YES\n" ...
"N\n" or something similar: "n\n", "no\n", ...
End-of-file occurs. scanf() returns EOF and feof(stdin)is true.
Input error occurs. scanf() returns EOF and ferror(stdin)is true. (Rare)
Something else. Usually a user mistake.
In general, best to avoid scanf()and use fgets().
Yet sticking with scanf():
Read in a line of input. Use a space to consume leading white-spaces including a prior line's '\n'.
unsigned char buf[80];
buf[0] = 0;
int retval = scanf(" %79[^\n]", buf);
Then disambiguate. Suggest case insensitivity. Perhaps allow just the first letter or the whole word.
if (retval == EOF) {
if (feof(stdin) {
puts("End-of-file");
} else { // Input error expected
puts("Input error");
}
} else {
for (unsigned char *s = buf; *s; s++) {
*s = tolower(*s);
}
if (strcmp(buf, "y") == 0 || strcmp(buf, "yes") == 0) {
puts("Yes");
} else if (strcmp(buf, "n") == 0 || strcmp(buf, "no") == 0) {
puts("No");
} else {
puts("Non- yes/no input");
}
}
How about a helper function to handle Yes/No, True/False, ....?
// Return first character on match
// Return 0 on no match
// Return EOF on end-of-file or input error
int Get1of2(const char *prompt, const char *answer1, const char *answer2) {
if (prompt) {
fputs(prompt, stdout);
}
unsigned char buf[80];
buf[0] = 0;
int retval = scanf(" %79[^\n]", buf);
if (retval == EOF) {
return EOF;
}
for (unsigned char *s = buf; *s; s++) {
*s = tolower(*s);
}
if ((buf[0] == answer1[0] && buf[1] == 0) ||
strcmp(buf, answer1) == 0) {
return buf[0];
}
if ((buf[0] == answer2[0] && buf[1] == 0) ||
strcmp(buf, answer2) == 0) {
return buf[0];
}
return 0; // None of the above.
}
Sample calls:
int yn = Get1of2("Single provider (y/n)? ", "yes", "no");
int rb = Get1of2("What is your favorite color? (r/b)? ", "red", "blue");
int tf = Get1of2("Nineveh the capital of Assyria? (t/f)? ", "true", "false");