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
Show 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
...