How to add a timer in a C++ program [closed]

If your platform has conio.h available and your compiler supports C++11 (including <chrono>) you can do it like this:

#include <iostream>
#include <chrono>
#include <conio.h>

int main(int argc, char* argv[]){
  std::chrono::time_point<std::chrono::system_clock> start;
  start = std::chrono::system_clock::now(); /* start timer */
  while(true){
    __int64 secondsElapsed = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now()-start).count();
    if(secondsElapsed >= 20){ /* 20 seconds elapsed -> leave main lopp */
      break;
    }
    if(_kbhit()){ /* keypressed */
      char c = _getch(); /* get character */
      std::cout << c; /* output character to stdout */
    }
  }
  return 0;
}

After 20 seconds are passed the programm terminates – until that, you can enter characters to the console window (tested on Windows 7 with Visual Studio 2012).

See also the documentation for _kbhit(), _getch() and <chrono>.

Leave a Comment