peek at input buffer, and flush extra characters in C

Carson Myers picture Carson Myers · May 10, 2009 · Viewed 9.1k times · Source

If I want to receive a one character input in C, how would I check to see if extra characters were sent, and if so, how would I clear that?

Is there a function which acts like getc(stdin), but which doesn't prompt the user to enter a character, so I can just put while(getc(stdin)!=EOF);? Or a function to peek at the next character in the buffer, and if it doesn't return NULL (or whatever would be there), I could call a(nother) function which flushes stdin?

Edit

So right now, scanf seems to be doing the trick but is there a way to get it to read the whole string, up until the newline? Rather than to the nearest whitespace? I know I can just put "%s %s %s" or whatever into the format string but can I handle an arbitrary number of spaces?

Answer

dirkgently picture dirkgently · May 10, 2009

You cannot flush the input stream. You will be invoking undefined behavior if you do. Your best bet is to do:

int main() {
  int c = getchar();
  while (getchar() != EOF);
  return 0;
}

To use scanf magic:

#include <stdio.h>
#include <stdlib.h> 

#define str(s) #s
#define xstr(s) str(s)
#define BUFSZ 256

int main() {
  char buf[ BUFSZ + 1 ];
  int rc = scanf("%" xstr(BUFSZ) "[^\n]%*[^\n]", buf);
  if (!feof(stdin)) {
    getchar();
  }
  while (rc == 1) {
    printf("Your string is: %s\n", array);
    fflush(stdout);
    rc = scanf("%" xstr(LENGTH) "[^\n]%*[^\n]", array);
    if (!feof(stdin)) {
        getchar();
    }
   }
   return 0;
}