samedi 23 janvier 2021

i need it to add one hour to HH:MM:SS but it becomes AM when it is supposed to be PM

I need help with my code the time when I hit 1 on my if statement shows in main(). It is AM when it is supposed to be PM. I believe it is getting hung up from my GET12Hour, and Get24hour functions, because when I switch the calls to me functions it works just fine but both don't output 24 hour clocks than 12 hours. How do I fix this. this is my first project in C++. please help.

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

void Get24Hour(){
    time_t now = time(0);
    tm* lt = localtime(&now);

    cout << lt->tm_hour << ":";
    cout << lt->tm_min << ":";
    cout << lt->tm_sec;
    return;

}

void Get12Hour(){
    time_t now = time(0);
    tm* lt = localtime(&now);
    string amOrPm;

    if(lt->tm_hour > 12){
        lt->tm_hour = lt->tm_hour - 12;
        amOrPm = "PM";
        cout << lt->tm_hour << ":";
    }
    else{
        cout << lt->tm_hour << ":";
        amOrPm = "AM";
    }
    cout << lt->tm_min << ":";
    cout << lt->tm_sec << " ";
    cout << amOrPm;
    return;
}
void DisplayMenu(){
    cout << "1- Add One Hour" << endl;
    cout << "2- Add One Minute" << endl;
    cout << "3- Add One Second" << endl;
    cout << "4- Exit Program" << endl;
}

int main()
{

    time_t now = time(0);
    tm* lt = localtime(&now);
    string amOrPm;
    int userInput;

    cout << "24 hour clock" << endl;
    Get24Hour();
    cout << endl;

    cout << "12 hour clock" << endl;
    Get12Hour();
    cout << endl;

    DisplayMenu();


    cin >> userInput;
    if(userInput == 1){
        lt->tm_hour = lt->tm_hour + 1;
        cout << "24 hour clock" << endl;
        cout << lt->tm_hour << ":" << lt->tm_min << ":" << lt->tm_sec <<endl;

        cout << "12 hour clock" << endl;
        if(lt->tm_hour > 12){
            lt->tm_hour = lt->tm_hour - 12;
            amOrPm = "PM";
            cout << lt->tm_hour << ":";
        }
        else{
            cout << lt->tm_hour << ":";
            amOrPm = "AM";
        }
        cout << lt->tm_min << ":";
        cout << lt->tm_sec << " ";
        cout << amOrPm;
    }
    else if(userInput == 2){

    }
    else if (userInput == 3){

    }
    else if(userInput == 4){

    }
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire