I'm trying to write a simple program that asks a user to choose from a menu in a loop. I use getchar() to get the input, however i've noticed that when I enter a char and press 'Enter' the program makes two loops (as if i pressed twice) one the char as an input and another for 'Enter' as an input.
How do I fix this?
The easiest way is to filter out the enter key as the return value from getchar
char c = (char)getchar();
if ( c != '\n' ) {
...
}
getchar()
returns the first character in the input buffer, and removes it from the input buffer. But other characters are still in the input buffer (\n
in your example). You need to clear the input buffer before calling getchar()
again:
void clearInputBuffer() // works only if the input buffer is not empty
{
do
{
c = getchar();
} while (c != '\n' && c != EOF);
}
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