I have written a simple timer. By pressing “s” (without pressing enter for submitting it) the timer (for-loop) will start. It is a no-ending loop. I want to stop it as soon as user presses “s”, just like in the way I start it. As soon as pressing “s” (without pressing enter for submitting it) the loop should stop. How to do it?
#include <iostream>
#include <stdlib.h>
#include <conio.h>
using namespace std;
int main()
{
char ch;
int m=0,h=0;
if ((ch = _getch()) == 's')
for (int i=0;;i++)
{
cout << "h m s" << endl;
cout << h << " " << m << " " << i;
system("CLS");
if (i==60) {i=0;m+=1;}
if (m==60) {m=0;h+=1;}
if (h==24) {h=0;}
}
return 0;
}
Have a separate
volatilevariable which you use as a condition to exit from the loop.On a separate thread (only way to listen for user input and keep the loop going at the same time) modify the variable when the user presses
"s".Note that you’re very likely to overflow
ibefore you get to press anything.