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.
#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;
}
Comments
Leave a comment