카테고리 없음

Exercise 16.1: Exceptions

07514673 2021. 12. 20. 14:55

Exercise 16.1: Exceptions

Here is the problem specification:

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. Similar conventions for the invalid values of minutes and seconds.

Sample Run

Enter hours: 14

The value of hr must be between 0 and 12.
Enter hours: -2

The value of hr must be between 0 and 12.
Enter hours: 5

Enter minutes: 70

The value of minutes must be between 0 and 59.
Enter minutes: 30

Enter seconds: -2

The value of seconds must be between 0 and 59.
Enter seconds: 45

Enter AM or PM: AM

24 hour clock time: 5:30:45

 

#include <iostream>
#include <string>
using namespace std;
class invalidHr{
    string msg = "The value of hr must be between 0 and 12";
    public:
    invalidHr(){}
    string what(){return msg;}
};
class invalidMin{
    string msg = "The value of minutes must be between 0 and 59.";
    public:
    invalidMin(){}
    string what(){return msg;}
};
class invalidSec{
    string msg = "The value of seconds must be between 0 and 59.";
    public:
    invalidSec(){}
    string what(){return msg;}
};
int main(){
    bool HourTryAgain=true;
    bool MinTryAgain=true;
    bool SecTryAgain=true;
    int hr, min, sec;
    while(HourTryAgain)
    {
        try
        {
            cout<<"Enter hours: ";
            cin>>hr;
            if(hr > 12 || hr < 1) throw invalidHr();
            HourTryAgain=false;
           while(MinTryAgain)
            try
            {
                cout<<"Enter minutes: ";
                cin>>min;
                if(min > 59 || min < 0) throw invalidMin();
                MinTryAgain=false;
                while(SecTryAgain)
                try
                {
                    cout<<"Enter seconds: ";
                    cin>>sec;
                    if(sec > 59 || sec < 0) throw invalidSec();
                    SecTryAgain=false;
                }
                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<<"Enter AM or PM:";
    string choice; cin>>choice;
    if(choice == "PM" && hr != 12) hr += 12;
    if(hr == 12 && choice == "AM" || hr == 24) hr = 0;
    cout<<"24 hour clock time: "<<hr<<":"<<min<<":"<<sec<<endl;
    return 0;
}