how to get a keypress within fixed amount of time

the program has to accept a keypress. It should wait for some fixed amount of time. If a key is pressed within this time, the program should call a function. If a key is not pressed in this time limit the program should continue its normal execution. Can someone please help me with the code ? The problem with getch() is that it essentially requires you to press a key and it does not allow other instructions to execute until the key is pressed.
Last edited on
closed account (28poGNh0)
If I understand what you seek maybe this program is what you looking for

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# include <iostream>
# include <conio.h>
# include <ctime>
using namespace std;

void yourFunction(char ch,double timeLimit);

int main()
{
    int fixedAmountTime = 9;//9 seconds
    double timeLimit = 0;

    while(true)
    {
        timeLimit = fixedAmountTime*1000-clock();
        if(kbhit()&&timeLimit>0)
        {
            char ch = getch();
            yourFunction(ch,timeLimit);
        }

        /// Normal excution
    }

    return 0;
}

void yourFunction(char ch,double timeLimit)
{
    cout << "You pressed " << ch << " You still have " << timeLimit/1000 << " sec" << endl;;
}


hope that helps
Can u modify the program a bit using delay()
@Techno:

That would do normal execution if a key was not pressed regardless of the timeLimit.
I suggest:

1
2
3
4
5
6
7
8
9
10
        const int timeLimit = 10; //Within ten seconds
	for(int i = 0; i < timeLimit; i++)
	{
		Sleep(1000); // Waits one second Defined in Windows.h, or just use the ctime version
		if(_kbhit()) //kbhit() and getch() are depricated. VS 2012 says to use these
		{
			myfunction(_getch());
		}
	}
	//Normal execution 

Last edited on
Topic archived. No new replies allowed.