This can not be done with pure C ++ since it depends on the operating system and console used. ( Font )
An alternative is to use the kbhit()
function available in the conio.h
library. It checks if any keys have been pressed, so just call the function before scanf
. However, we need to look at why there are distinct implementations for Windows and Linux . ( Font )
In Windows, you can also use the ReadConsoleInput
to read and empty the console input buffer. Note that this function also captures mouse events, so you need to check the event type received .
One consideration for all this is that, depending on what you want, it is not good to do checks in a loop. That wastes CPU. One approach to solving this is to create new threads to make the processing "heavy" and leave the main thread responsible for reading and writing on the console.