I have a simple timer. It's in a function running in a thread separate from the main. Using std::future
, the function returns a simple bool that says whether the timer has hit a specific number or not.
I am using getch();
to see if the user pressed a letter key.
If the timer returns true, that it hit a designated number, I need to cancel getch()
; and move to the next step in the code. Moving to the next step is easy.
It's been 2 weeks and I can not find a solution to my problem.
The Problem: How on earth, can I interrupt or cancel a call to getch();
? Is this even possible?
I'm using getch();
to identify which letter keys were pressed.
C++11 Visual Studio.
The operating system must provide access to the keyboard. So on Windows for example, the best is probably to deal with input on the operating system's terms as described here.
With the standard c++ library functions one can read characters from the
std::cin
stream. The problem is that those characters are only passed from the operating system after the user presses Enter (which also adds a newline\n
character).If you can tolerate the need to press the return key after a character is typed then the following could work. This program executes
get()
in a separate thread so that it doesn't block the program if no key is pressed or if Enter is not pressed and only uses standard c++11. This program will however not complete (i.e. join the thread) unless the user typesq
or sends theEOF
.Output: