I need to add a timeout function for getchar() in my program.
What do I do so that when my program reaches the instruction getchar(), it will only wait for a certain amount of time for the user to make a keystroke and if the user does not make a keystroke within the given time limit, the program will "skip" the getchar()?
The operating system does not support the conio.h library so kbhit is not an option.
How to add a timeout when reading from `stdin` I found this question is helpful.
Another method is using multithreading.
If you are using c++11, you can make use of
condition_variable::wait_for()
as a timer thread. And the original getchar() is blocking on another thread.Here is an example:
When there is a keystroke, main thread will notify the worker thread.
This is usually achieved by using
select()
onstdin
. Another solution would be usingalarm()
and a dummy SIGALRM handler to interrupt thegetchar()
call (only working on POSIX systems though).