Inside Man
Inside Man

Reputation: 4297

Stop a loop by pressing a key in real-time

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;
}

Upvotes: 1

Views: 1585

Answers (1)

Luchian Grigore
Luchian Grigore

Reputation: 258618

Have a separate volatile variable 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".

volatile bool keepLoopGoing = true;

//loop
for (int i=0; keepLoopGoing ;i++)
    cout << i << endl;

//user input - separate thread
while ( keepLoopGoing )
{
   cin >> input;  // or getchar()
   if ( input == "s" )
      keepLoopGoing = false;
}

Note that you're very likely to overflow i before you get to press anything.

Upvotes: 3

Related Questions