This document provides a beginner-friendly explanation of the C++ alarm clock program. The program allows the user to set an alarm for a specific time, and it continuously checks the system's current time until the alarm time is reached. Once the set time is matched, the program triggers an alarm message.
1. Import Required Libraries
#include <iostream>
#include <thread>
#include <chrono>
#include <ctime>
2. Alarm Clock Function
void alarmClock(int setHour, int setMinute, int setSecond) {
while (true) { time_t now = time(0);
tm *ltm = localtime(&now);
int currentHour = ltm->tm_hour;
int currentMinute = ltm->tm_min;
int currentSecond = ltm->tm_sec;
cout << "Current Time: " << currentHour << ":" << currentMinute << ":" << currentSecond << endl;
if (currentHour == setHour && currentMinute == setMinute && currentSecond == setSecond) {
cout << "\n*** Alarm ringing! Time to wake up! ***\n" << endl;
break;
}
this_thread::sleep_for(chrono::seconds(1));
}
}
3. Main Function
int main() {
int hour, minute, second;
cout << "Enter alarm time (HH MM SS): ";
cin >> hour >> minute >> second;
cout << "\nAlarm set for " << hour << ":" << minute << ":" << second << "\n";
thread alarmThread(alarmClock, hour, minute, second);
alarmThread.join();
return 0;
}
This simple C++ alarm clock demonstrates the use of time functions, loops, and multi-threading. It continuously checks the time until the alarm goes off. The knowledge gained from this program can be applied to build more complex time-based applications in C++.
71 videos|48 docs|15 tests
|