Search code examples
cinputbuffergetch

How to avoid pressing enter in a portable context to empty the input buffer?


The Problem

I usually use fgets() or getchar(), but now I need to use getch(), because I don't want to press enter to send a char to the input buffer.

What I tried

When I used fgets() and getchar() I also used:

int c;
while ((r = getchar()) != '\n' && r != EOF){}

But now if I use it before getch() it requires me to press enter, which I don't want.

Is there any portable solution to empty the input buffer?


Solution

  • You can't use getch() in a portable context because it's a conio.h, not a stdio.h function. There are lengthy threads on this topic and the overall assumption is that it can't be done, only worked around in a dodgy manner.

    I suggest you revise your code and application to check weather or not you need to input with a getch() like function, or if there are other ways to do achieve the same goal. Depending on the use case it's often only cosmetic not to press Enter.