Reputation: 23
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.
Upvotes: 2
Views: 200
Reputation: 112366
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.
Upvotes: 9
Reputation: 14688
Terminal input and output by default is line buffered.
You can put the input into single character mode (as opposed to line mode), but the method differs on each OS -- On linux you would use ioctl
calls to reconfigure the input and you would change the vtime
and vmin
parameters to say that you want one character at a time -- Also, see this question termios VMIN VTIME and blocking/non-blocking read operations
Upvotes: 0
Reputation: 182769
Terminals are, by default, in line mode. There's no guarantee a terminal even supports anything else. The C language is a standard that was designed to work with even the most simple devices and doesn't assume that your terminal has sophisticated capabilities like cursor addressing, erase, or character-level control.
If you want anything fancy, you leave the realm of pure C and start using specific information you have about the characteristics of particular hardware you have or availability of libraries on your platform.
Upvotes: 6