Real-Time Clock System in C++ that Updates Every Second

In this exercise, you will develop a real-time clock system in C++ that updates every second. The goal is to create a simple digital clock that continuously updates the time every second. The program will use system time functions to retrieve the current time and display it in a readable format, such as hours, minutes, and seconds. The system will then refresh every second using a loop and delay to simulate the passage of time. This is a great exercise to learn about time management in C++ and working with loops and delays.

Group

Real-Time Programming in C++

Objective

Write a C++ program that continuously displays the current time and updates every second. Use the time library to get the current system time and format it to display hours, minutes, and seconds. The program should update the clock in real-time without user input and should display the updated time every second.

Develop a real-time clock system that updates every second.

Example C++ Exercise

 Copy C++ Code
#include <iostream>  // Include the input-output stream library
#include <chrono>     // Include the chrono library for time-related functions
#include <thread>     // Include the thread library to implement delays
using namespace std;

// Function to display the current time in hours, minutes, and seconds
void displayTime() {
    while (true) {  // Infinite loop to continuously update the time
        // Get the current system time
        auto currentTime = chrono::system_clock::now();

        // Convert current time to a time_t type
        time_t timeNow = chrono::system_clock::to_time_t(currentTime);

        // Format the time to display it in a readable format
        cout << "\r" << ctime(&timeNow) << flush;

        // Wait for 1 second before updating the time again
        this_thread::sleep_for(chrono::seconds(1));
    }
}

int main() {
    // Call the displayTime function to start the clock
    displayTime();
    return 0;
}

 Output

Sun Apr 16 12:34:56 2025
Sun Apr 16 12:34:57 2025
Sun Apr 16 12:34:58 2025
...

Share this C++ Exercise


More C++ Programming Exercises of Real-Time Programming in C++

Explore our set of C++ Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C++. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C++.