Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

getchar

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?

like image 995
SnapDragon Avatar asked Oct 19 '10 15:10

SnapDragon


2 Answers

The easiest way is to filter out the enter key as the return value from getchar

char c = (char)getchar();
if ( c != '\n' ) {
  ...
}
like image 165
JaredPar Avatar answered Sep 19 '22 18:09

JaredPar


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);
}
like image 34
KeatsPeeks Avatar answered Sep 19 '22 18:09

KeatsPeeks