Well, I'm new to C, previously a programmer in PHP. Sorry if I'm making any obvious mistakes.
Anyways, I'm writing a simple CLI program that answers to Y/N.
If I type in Y, everything works as expected. However, when I type in N, it executes both the else if, and the else conditionals.
(Y/N)?: N
Wrong answer...
(Y/N)?: Please type Y or N.
(Y/N)?:
When I type in something random, the else is executed for every character inputted. No idea why:
(Y/N)?: asdf
Please type Y or N.
(Y/N)?: Please type Y or N.
(Y/N)?: Please type Y or N.
(Y/N)?: Please type Y or N.
(Y/N)?: Please type Y or N.
(Y/N)?:
Here is the code:
Code:
#include <stdio.h>
void yesno() {
char choice;
printf("(Y/N)?: ");
scanf("%c", &choice);
if (choice == 'Y') {
printf("<333");
}
else if (choice == 'N') {
printf("Wrong answer...\n");
yesno();
}
else {
printf("Please type Y or N.\n");
yesno();
}
}
int main()
{
//ask_question();
yesno();
fflush(stdin);
getchar();
return 0;
}
Again, sorry if I did something really stupid or obvious.
Thanks tons!