Can’t do this with pure C++ as it depends on the operating system and console used. (Source)
An alternative is to use the function kbhit()
available in the library conio.h
. It checks if any key has been pressed, so just Chaar the function before scanf
. However, it is necessary to pay attention because there are different implementations for Windows and Linux. (Source)
In Windows, you can also use the function ReadConsoleInput
to read and empty the input buffer of the console. Note that this function also captures mouse events, so you need to check the type of event received.
One consideration about all this is that, depending on what you want, it is not good to do checks on a loop. This wastes CPU. One approach to solve this is to create new threads to do the "heavy" processing and leave the main thread responsible for reading and writing on the console.
handles with interruption. The way to do this depends on the language, your program is to run on desktop?. creates a keyboard interrupt that runs something when a key is pressed. are you using c or c++? so answer I search and complement the answer
– Joannis
you can post your code?
– Joannis