Is there a function in C++ that waits for the user to press a key and move after sometime if the key not press?
2012-12-28 23:40:52 UTC
Such as, In visual C++, we can take a key from the user by:
key=getch();
Now the program execution will not continue until the user presses a key; I want that the program should continue to execute if the user does not press any key within 5 seconds.
Three answers:
2012-12-29 00:00:55 UTC
here's the pseudocode
void GetInput(){
key=getch();
}
int main(){
~~code here
createThread(GetInput);
while( key has not changed){
~~loop for 5 seconds or so
}
}
2012-12-29 08:01:17 UTC
So what you should do is create a thread, and if you don't hear from it in 5 seconds kill it and continue.
Use WaitForSingleObject() windows function. Look it up under msdn
If you're on Linux:
use
pthread_cond_timedwait
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
ts.tv_sec += 10; // ten seconds
while (!some_condition && ret == 0)
ret = pthread_cond_timedwait(&cond, &mutex, &ts);
roger
2012-12-29 18:06:26 UTC
simple solution:
check the time -- store
loop checking the time and kbhit()
if kbhit() is true then get the character hit and do something
else if time is 5 seconds more than the first (stored) time go do something else.
ⓘ
This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.