1

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;
}
Inside Man
  • 4,194
  • 12
  • 59
  • 119

1 Answers1

3

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.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • I did not understand your meaning too well. I'm amateur. I do not want to use cin >> s; so user presses a key then I use a if command for checking if it is "s" then break the loop. It is not real-time, it stops screen for pressing a char then it will continue, I need something that affects in real-time. – Inside Man May 27 '12 at 14:13
  • 1
    @Stranger if you start a different thread to listen for input, it won't "stop" the screen. Read up on threads. – Luchian Grigore May 27 '12 at 14:14
  • @Stranger see this question - http://stackoverflow.com/questions/421860/c-c-capture-characters-from-standard-input-without-waiting-for-enter-to-be-pr – Luchian Grigore May 27 '12 at 14:41