1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
#include <iostream> #include <iomanip> #include <ctime> #include <chrono> #include <thread> using namespace std; void displayTime(int hours, int minutes, int seconds) { // Clears the screen (works on most consoles) system("clear"); // Use "cls" for Windows // Display the time in HH:MM:SS format cout << setfill('0') << setw(2) << hours << ":" << setfill('0') << setw(2) << minutes << ":" << setfill('0') << setw(2) << seconds << endl; } int main() { while (true) { // Get the current time from the system time_t now = time(0); tm *ltm = localtime(&now); int hours = ltm->tm_hour; int minutes = ltm->tm_min; int seconds = ltm->tm_sec; // Display the time displayTime(hours, minutes, seconds); // Wait for one second this_thread::sleep_for(chrono::seconds(1)); } return 0; } |
Explanation:
- Getting the Current Time:
- The program uses the C++ standard library to get the current time from the system. The
time(0)
Advertisement - The
localtime()
function converts this time into atm
structure, which contains the current time broken down into components such as hours (tm_hour
Advertisementtm_min
), and seconds (tm_sec
).
- The program uses the C++ standard library to get the current time from the system. The
- Displaying the Time:
- The
displayTime
function takes the hours, minutes, and seconds as parameters and prints them in theHH:MM:SS
format. - The
setfill('0')
andsetw(2)
functions from the<iomanip>
library are used to ensure that each time component is always two digits long, with leading zeros if necessary.
- The
- Clearing the Console:
- The
system("clear")
command is used to clear the console screen before updating the time display. This command works on Unix-like systems. On Windows, you would usesystem("cls")
.
- The
- Infinite Loop and Delay:
- The
while (true)
loop runs indefinitely, continuously updating the time display. - The
this_thread::sleep_for(chrono::seconds(1))
command pauses the execution for one second before updating the time again. This creates the ticking effect of a digital clock.
Advertisement - The
Possible Enhancements:
- 12-Hour Format: Add an option to switch between 24-hour and 12-hour (AM/PM) formats.
- Customizable Interface: Allow users to change the clock’s appearance, such as the color or the format of the time display.
- Stopwatch or Timer: Extend the program to include a stopwatch or countdown timer functionality.
- GUI Version: Create a graphical user interface (GUI) version using libraries like SFML or Qt for a more visually appealing clock.