How do I flush scanf buffer in C?

Oct 10, 2014 at 7:53pm
Hello!

I am writing a program and am asking the user to enter a number between 1-12.
If they do not, they will be promoted over and over again to enter a number between 1-12.

However, if the user enters a letter or anything else scanf seems to stop working and then my loop goes out of control.

How do I fix this.

Thank you in advance.
Oct 10, 2014 at 8:01pm
Could you please post some code?
Oct 10, 2014 at 10:14pm
The scanf() function will not read anything that does not conform to the required input type.

However, the following mantra will help:

The user will always press Enter after every input.

With that in mind, if you ask the user to enter a number, but he enters the wrong thing, he will still have had to press Enter.

So, just read and discard everything up to and including the newline.

1
2
3
4
void sync_eol()
{
  while (getchar() != '\n') { }
}
1
2
3
4
5
6
  while (1)
  {
    int n = scanf( ... );
    if (n < N) sync_eol();
    else break;
  }

(N is, of course, the number of items you are trying to read, which should likely be one.)

Hope this helps.
Topic archived. No new replies allowed.