Sorry I'm new at this so the answer is probably obvious but.. Can someone explain to me why for my code which takes input, only works when I press enter and then input my letter for the else if?
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
printf("Question?\nType Y for yes or N for no");
if(getc(stdin) == 'N')
printf("That is not the correct answer\n");
else if(getc(stdin) == 'Y')
printf("Good Job! That is the correct answer\n");
else
printf("That's not a valid answer\n");
return 0;
}
What happens is, if I type "N" then it correctly responds with "That is not the correct answer" but if I type "Y" it says "That's not a valid answer"; however if I press enter and then type "Y" it correctly responds "Good Job! That is the correct answer!". This is probably something obvious because again I'm very new to coding but any help is appreciated.
you're reading two characters -- one at the Y branch and one at the N branch. Try something like
int c; /* pop quiz: why int? */
c = getc(stdin);
if (c == 'N') ...
Update That said, you're still going to need to type RETURN to get the character in. But right now the logic isn't right. Once you get the logic right, look into "raw" and "rare" mode for the terminal driver.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With