Using getchar() on c gets the 'Enter' after input

SnapDragon picture SnapDragon · Oct 19, 2010 · Viewed 65.5k times · Source

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?

Answer

KeatsPeeks picture KeatsPeeks · Oct 19, 2010

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);
}