Search code examples
c++functioncountdownclockstopwatch

How can I generate a stopwatch/countdown with the following code in C++?


I'm trying to create a timer function that prints a timer of 2 minutes (in M:S form) that ticks down by itself. I have the following code:

    void startTimer(){
    srand(time(0));

    clock_t start_t, end_t;
    clock_t start = clock();        
    clock_t end = clock();
    float seconds = (float)(end - start) / CLOCKS_PER_SEC;

    printf("%d", start, seconds);
    }

Solution

  • The code that you have can measure the time that it takes to run a piece of code. What you need here is just to:

    • Print the count down
    • Sleep for one second

    and do it in a loop.

    #include <iostream>
    #include <unistd.h>
    
    
    int main(){
      for (int i = 120; i >=0; i--){
        std::cout << std::to_string(i/60) <<":" << std::to_string(i%60) <<std::endl; 
        sleep(1);
      }
      return 0;
    }