Patrik Bak
Patrik Bak

Reputation: 538

C++ How to stop a countdown timer?

I've got this simple countdown timer:

#include <iostream>     
#include <windows.h>
using namespace std;

int main ()
{
    for(int i=9; i>=0; i--)
    {
        cout << i;
        cout << string(1,'\b');
        Sleep(1000);
    }
    system("pause > nul");
    return 0;
}

I would like to pause it whenever I press 'P' and then resume it with 'R'.

How should I modify it ? In generally, is possible to make timer which is running while I am continuing in other operations (like cin, cout...) ?

Upvotes: 0

Views: 2187

Answers (3)

GingerPlusPlus
GingerPlusPlus

Reputation: 5606

Pausing timer

If you're not interested in portability, you can #include<conio.h> (available on Windows) and use kbhit() to check if there is something to read in keyboard buffer, and use getch() to check which key was pressed, example implementation:

#include<iostream>
#include<conio.h>     
#include<windows.h>
using std::cout;

int main (){
    for(int i=9; i>=0; i--){
        if(kbhit()){
            auto got=getch();
            if(got=='p'||got=='P'){
                cout<<"PAUSED, R to resume.\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b";
                do auto got=getch(); while(got!='r'&&got!='R');
            }
        }
        cout << i << '\b';
        Sleep(1000);
    }
    do; while(getch()!='\n'); /*don't use system("anything") when unnecessary,
                               *it calls external program to do work for your.
                               */
}

Using std::cin while timer is running

std::cin locks thread execution. If you want to use it while timer is running, I redirect you to @Dogbert's answer.

Upvotes: 0

Cloud
Cloud

Reputation: 19333

There are two approaches to this. You could either use an existing library like ncurses:

#include <curses.h>

int main(void) {
  initscr();
  timeout(-1);
  int c = getch();
  endwin();
  printf ("%d %c\n", c, c);
  return 0;
}

If you don't want to use an external library, you could write a multithreaded application. In one thread, you have your countdown function running, with an additional check, something like:

for(int i=9; i>=0; )
{
    pthread_mutex_lock(&someMutex);
    if (someBool == true) {
      // do someting else
    } else {
      cout << i;
      cout << string(1,'\b');
      Sleep(1000);
      i--;
    }
    pthread_mutex_unlock(&someMutex);
}

Then, in the other thread, you wait on user input using getchar or some other mechanism.

Upvotes: 1

Jacques de Hooge
Jacques de Hooge

Reputation: 6990

You'll need threads to do this, or timers that use them implicitly in combination with a callback.

Upvotes: 0

Related Questions