4

Exactly what it says on the tin. Is there a way for me to empty out the input buffer in preparation for further user input without using the undefined fflush(stdin) or a looped getchar()?

I'm trying to write a small input function that isn't vulnerable to buffer overflows. For this, I've used fgets(entered_text, 30, stdin); which works as promised.

However, in the event of overflow, I have stuff remaining in the input buffer that gets read when I next call the input function. I want to empty the buffer to avoid this.

fflush(stdin) is supported, but not defined. http://c-faq.com/stdio/stdinflush2.html suggests I use a loop of getchars, but the problem is that if the input buffer is empty, it will request a character and force me to press two 'enter's.

Is there a way for me to check if the input buffer is empty, or to empty it by other means?

Thanks in advance.

alk
  • 69,737
  • 10
  • 105
  • 255
firepanda
  • 49
  • 3
  • If `fgets` can't store all of the data, then the last character will not be '\n' which means you can keep reading more data. I never understood why people think they need to "flush the input buffer" in this situation. It is easy to see if there is more data. Keep reading characters until either a '\n' occurs or EOF. Those are the only two possibilities (otherwise its a normal character). – Brandin Feb 14 '14 at 10:17
  • This would do the job: http://stackoverflow.com/a/21709726/694576 – alk Feb 14 '14 at 10:50

2 Answers2

2

You can check if the input is empty by using select().

Some related information is here: C select() timeout STDIN single char (no ENTER)

Community
  • 1
  • 1
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
0

You can use fpurge function to clear the buffer stream. Please read the man page of fpurge for more information.

Amit
  • 81
  • 5