Answer to Question #251181 in C++ for HelloWorld

Question #251181

Write a program that prompts the user to enter time in 12-hour notation. The program then outputs the time in 24-hour notation. Your program must contain three exception classes: invalidHr, invalidMin, and invalidSec. If the user enters an invalid value for hours, then the program should throw and catch an invalidHr object. Follow similar conventions for the invalid values of minutes and seconds.


1
Expert's answer
2021-10-14T03:45:08-0400
#include <iostream>
#include <string>
using namespace std;
class invalidHr{
    string msg = "Invalid hour input";
    public:
    invalidHr(){}
    string what(){return msg;}
};
class invalidMin{
    string msg = "Invalid minute input";
    public:
    invalidMin(){}
    string what(){return msg;}
};
class invalidSec{
    string msg = "Invalid second input";
    public:
    invalidSec(){}
    string what(){return msg;}
};
int main(){
    int hr, min, sec;
    try
    {
        cout<<"Enter hours: ";
        cin>>hr;
        if(hr > 12 || hr < 1) throw invalidHr();
        try
        {
            cout<<"Enter minutes: ";
            cin>>min;
            if(min > 59 || min < 0) throw invalidMin();
            try
            {
                cout<<"Enter seconds: ";
                cin>>sec;
                if(sec > 59 || sec < 0) throw invalidSec();
            }
            catch(invalidSec &e)
            {
                std::cerr << e.what() << '\n';
                return -1;
            }
            
        }
        catch(invalidMin &e)
        {
            std::cerr << e.what() << '\n';
            return -1;
        }
        
    }
    catch(invalidHr &e)
    {
        std::cerr << e.what() << '\n';
        return -1;
    }
    cout<<"1. AM\n2. PM\n";
    int choice; cin>>choice;
    if(choice == 2 && hr != 12) hr += 12;
    if(hr == 12 && choice == 1 || hr == 24) hr = 0;
    cout<<"Time in 24 hour format: "<<hr<<":"<<min<<":"<<sec<<endl;
    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS