I must be missing something here. I am having trouble when I try to get an input. The numbers work fine, but once you get the correct answer, the area:
printf("Would you like to try another one? (y/n)\n");
scanf("%c", &yorn);
if(yorn == 'y')
getnum();
elseif(yorn == 'n')
return;
elseif(yorn != 'y' || yorn != 'n'){
printf("Invalid choice\n");
tryanother();
}
}
isn't right. It will print "Would you like to try another (y/n)." "Invalid Choice." "Would you like to try another (y/n)" then wait for your input... why is it doing this?
when you press 'y' followed by <Enter> key, there are two keys in the keyboard buffer -- so the second time through the code it is probably getting the '\n' key. you need to flush the keyboard buffer to remove the '\n'.
getchar(); //flush the keyboard buffer of the '\n' key
or you could use fgets() which will flush the '\n' too assuming the user types on 'y' followed by <Enter>. If anything else is typed then those keys will also be in the keyboard buffer. There is no easy standard solution to the problem. Make the buffer in the code below big enough and fgets() will probably be able to fill it with all the keys in the buffer.
I did not understand that if the size of the buf variable is 3 then after getting input "y" and "\n" how does stdin terminate the coming input i.e. what would be buf[2]??
lets say that instead of typing just y + '\n', you type a whole bunch of keys then '\n' at the end. fgets() will only grab from the keyboard buffer the number of keys that will fit in the buffer (sizeof the buffer - 1 for null terminator), the remaining keys will stay in the keyboard buffer until your program removes them. And the buffer returned by fgets() will contain '\n' only if there is one in the input stream.
The loop that dwks posted is probably the savest way to flush out (empty) the keyboard buffer that contains an unknown number of characters.
No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.