본문 바로가기

Programming language/C++

[C++] 알람시계 구현하기

소스코드

#include <iostream>
#include <ctime>
#include <thread>
#include <chrono>
using namespace std;

// Function to get the current time in HH:MM format
string getCurrentTime() {
    time_t now = time(0);
    struct tm timeinfo;
    localtime_r(&now, &timeinfo);
    char buffer[6];
    strftime(buffer, sizeof(buffer), "%H:%M", &timeinfo);
    return buffer;
}

int main() {
    cout << "Console Alarm Clock" << endl;
    cout << "Enter the alarm time (HH:MM): ";

    string alarmTime;
    cin >> alarmTime;

    while (true) {
        string currentTime = getCurrentTime();

        if (currentTime == alarmTime) {
            cout << "Alarm! It's " << alarmTime << "!" << endl;
            break; // Exit when the alarm time is reached
        }

        cout << "Current time: " << currentTime << "\r";
        cout.flush();

        // Sleep for a second before checking the time again
        this_thread::sleep_for(chrono::seconds(1));
    }

    return 0;
}

사용 방법

1. getCurrentTime 함수는 시간 함수와 strftime을 사용하여 HH:MM 형식의 현재 시간을 검색합니다.
2. 사용자에게 HH:MM 형식의 알람 시간을 입력하라는 메시지를 표시합니다.
3. 지정된 알람 시간과 현재 시간을 지속적으로 비교하는 루프에 들어갑니다. 일치하면 알람을 트리거하고 루프를 종료합니다.
4. 대기하는 동안 프로그램은 현재 시간을 표시하고 새 줄을 만들지 않고 현재 시간을 표시하도록 제자리에서 업데이트합니다.
5. this_thread::sleep_for 함수는 시간 확인 사이에 프로그램을 1초 동안 일시 중지하는 데 사용됩니다.

 

실행 결과

Console Alarm Clock
Enter the alarm time (HH:MM): 15:30
Current time: 15:29

이 예에서는 사용자가 15:30으로 알람을 설정하고 프로그램이 현재 시간을 지속적으로 확인합니다. 알람 시간에 도달하면 프로그램이 알람을 트리거합니다.

Current time: 15:30
Alarm! It's 15:30!

'Programming language > C++' 카테고리의 다른 글

[C++] 단어 카운터 구현  (0) 2023.10.07
[C++] 단위 변환기 소스코드  (0) 2023.10.07
[C++] 텍스트 기반 RPG 구현하기  (0) 2023.10.06
[C++] 온도 변환기 구현  (0) 2023.10.06
[C++] 틱택토 게임 구현  (1) 2023.10.06