Search code examples
cscanfinput-buffer

How do I clear input buffer after a failed scanf()?


I have a problem with scanf() and input buffer in my program.

First I ask the user for input :

char someVariable;
printf("Enter text: ");
scanf(" %c",&someVariable);

Then I have a loop that goes over the input one char at a time using scanf() until it reaches a newline.

The problem is that after the loop is done, somehow, there is still something in the buffer so this function (which is being called in a loop) gets called again and ruins the logic in my program.

How can I force clear the input buffer?

I can only use scanf() (assignment requirements)

void checkType(){
    char userInput;
    char tempCheckInput;
    printf("Enter Text: ");
    scanf(" %c",&userInput);
    while (userInput != '\n'){

        tempCheckInput = userInput;
        scanf("%c",&userInput);

Ignore the end of the loop; this is the part where I get the input.


Solution

  • how can i force clear the input buffer?

    In C, a stream, like stdin, cannot be cleared (in a standard way) as in "delete all input up to this point in time".

    Instead input can consume and toss (akin to "cleared") input up to a data condition.

    The usually way is

    int consume_rest_of_line(void) {
      int ch;
      while ((ch = getchar()) != '\n' && ch != EOF) {
        ;
      }
    }
    

    If limited to scanf()

    int consume_rest_of_line(void) {
      char ch;
      while (scanf("%c", &ch) == 1 && ch != '\n') {
        ;
      }
    }