I'm trying to write a basic timer program for kicks. Everything works, but I can't figure out how to make the timer stop when a key is pressed. A specific key or any key will do just fine. The code so far:
#include "iostream"
#include "windows.h"
usingnamespace std;
int main()
{
int a = 0; //seconds
int b = 0; //minutes
cout << "Press enter to start the timer.";
cin.ignore();
do
{
cout << b << ":";
if (a < 10)
{
cout << "0";
}
cout << a << "\n";
a++;
if (a == 60)
{
a = 0;
b++;
}
Sleep(10); //Sped up so I don't have to wait forever. Will be changed to 1000 eventually.
}while (b < 2); //To make sure the program stops eventually
return (0);
}
You can change it to whatever you want.
Note, that the GetAsyncKeyState() function can only be executed once every second, so the timer won't stop immediately, and will only stop if the specified key is being pressed at the exact same moment as GetAsyncKeyState() is being evaluated.
#include "iostream"
#include "windows.h"
usingnamespace std;
int main()
{
int a = 0; //seconds
int b = 0; //minutes
cout << "Press enter to start the timer, and press space to stop it.";
cin.ignore();
do
{
cout << b << ":";
if (a < 10)
{
cout << "0";
}
cout << a << "\n";
a++;
if (a == 60)
{
a = 0;
b++;
}
Sleep(1000);
}while (!GetAsyncKeyState(0x20));//0x20 is space
a--;
if(a < 0)
{
b--;
}
cout << "The final time was " << b << ":";
if (a < 10)
{
cout << "0";
}
cout << a << "\n";
cin.ignore();//to stop it from closing immediately
return (0);
}