How to create a timer in C++

In this blog, we are going to learn how to create a timer using C++ programming language. Here, we will create a timer that will take time as input from the user. This program notifies the user when the timer reaches zero. In this program, we will use a C++ header file called <ctime>. This header file contains functions to use and manipulate information about data and time.

A timer is a very basic need and we use it almost every day. By having a timer on your screens, you can work very conveniently.

Timer using C++

CODE

#include <iostream>
#include <ctime>
#include <unistd.h>

using namespace std;

void timer(int hours,int minutes,int seconds)
{
  int total_time = hours*60*60 + minutes*60 + seconds;
  time_t current_time = time(0);
  while(time(0)-current_time<total_time)
  {
    sleep(1);
  }
  cout<<"Time is up!!";
}

int main()
{
  int hours, minutes, seconds;
  cout<<"Enter the number of hours :";
  cin>>hours;
  cout<<"Enter the number of minutes :";
  cin>>minutes;
  cout<<"Enter the number of seconds :";
  cin>>seconds;
  timer(hours,minutes,seconds);
  return 0;
}

OUTPUT-

Enter the number of hours :0
Enter the number of minutes :0
Enter the number of seconds:30
Time is up!!

Background

This post contains the program to create a timer that can be used as a utility.
This program uses ctime and unistd.h libraries. The former library is used to get information about time and date, while the latter is used to control some system processes such as sleep, which pauses the system processes for a certain amount of time. Also, time_t is a data type in the ctime library that stores time.

Thank you.

Also read: Time function in C++

C++ program to create a stopwatch

Leave a Reply

Your email address will not be published. Required fields are marked *