how to handle the input buffer in c

Abdullah Al-Hatem picture Abdullah Al-Hatem · Dec 5, 2012 · Viewed 8.3k times · Source

I'm new to c programming and I'm facing this problem with my program
I have a loop that gets a char form the input buffer

while(c = getchar()){
    if(c == '\n') break;
    if(c == '1') Add();
    if(c == '2') getInput(); // this is where the headache starts
    ....
}

here is the getInput() function

void getInput()
{ 
    char ch = getchar();
    if(ch == '1') doSomething();
    ....
}

but when calling getchar() from the getInput() function it only gets characters that were left in the input buffer from the last call of getchar(). and what i want it to do is to get newly typed characters.

I've been googling for two hours for a decent way to clear the input buffer but nothing helped. So a link to a tutorial or an article or something is very appreciated and if there's another way to implement this then please tell me.

Answer

imulsion picture imulsion · Dec 5, 2012

This should work: (Example of clearing input buffer)

#include <stdio.h> 

int main(void)
{
  int   ch;
  char  buf[BUFSIZ];

  puts("Flushing input");

  while ((ch = getchar()) != '\n' && ch != EOF);

  printf ("Enter some text: ");

  if (fgets(buf, sizeof(buf), stdin))
  {
    printf ("You entered: %s", buf);
  }

  return 0;
}

/*
 * Program output:
 *
 Flushing input
 blah blah blah blah
 Enter some text: hello there
 You entered: hello there
 *
 */