Creating a digital Clock in C++

  • Last updated Apr 25, 2024

This tutorial will guide you through creating a digital clock using C++, providing a straightforward yet impactful introduction to this aspect of C++ programming.

A digital clock typically comprises hours, minutes, and seconds. In C++, time-related operations can be achieved by utilizing the <ctime> library. This library includes functions and structures to work with time-related data.

Here's the code that demonstrates the creation of a digital clock in C++:

#include <iostream>
#include <ctime>
#include <unistd.h>
using namespace std;

int main() {
    while (true) {
        time_t now = time(0);
        tm* timeInfo = localtime(&now);
        
        cout << "Time: " << timeInfo->tm_hour << ":" << timeInfo->tm_min << ":" << timeInfo->tm_sec << "\r";
        cout.flush();

        sleep(1);
    }
    return 0;
}

In this example, we first import necessary libraries: <iostream> enables input and output functionalities, <ctime> helps to work with time-related operations, and <unistd.h> provides the sleep() function for pausing execution. The use of namespace std directive allows using elements from the standard C++ library without explicit notation. Within the main() function, there is an infinite loop. The time(0) method retrieves the current time in seconds since the Unix epoch, while localtime(&now) converts this into a time structure. The cout statement prints the time, formatting it as hours, minutes, and seconds. The carriage return (\r) refreshes the time display without a new line. cout.flush() ensures immediate console output. sleep(1) suspends execution for one second, creating the one-second update interval. Finally, return 0; denotes successful program completion.

The output of the above code is as follows:

Time: 16:20:15