Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program that converts 24-hour time to 12-hour time. The following is a s

ID: 3607730 • Letter: W

Question

Write a program that converts 24-hour time to 12-hour time.

The following is a sample dialogue:

Enter time in 24-hour notation:

13:07

That is the same as 1:07 PM Again?(y/n)

y

Enter time in 24-hour notation:

10:15

That is the same as 10:15 AM Again?(y/n)

y

Enter time in 24-hour notation:

10:65

There is no such time as 10:65 Try again:

Enter time in 24-hour notation:

16:05

That is the same as 4:05 PM Again?(y/n)

n

End of program

You will define an exception class called TimeFormatMistake. If the user enters an illegal time, like 10:65 or even gibberish like 8&*68, then your program will throw and catch a TimeFormatMistake.

please post any solution other than already existed one.

Explanation / Answer

// C++ program to convert 24 hour to 12 hour

// format

#include<iostream>

using namespace std;

bool validate_time(int hh,int mm);

class TimeFormatMistake:public exception

{

  

};

bool validate_time(int hh,int mm)

{

// if hours greater than 23 return false as 24,25 .... are invalid

if(hh>23)

{

return false;

}

// if minutes are greater than 59 return false as 60,61 .... are invalid

if(mm > 59)

{

return false;

}

return true;

}

void get_time_validate(string str)

{

int result_hrs;

string result;   

// Get hours

int h1 = (int)str[1] - '0';

int h2 = (int)str[0] - '0';

//23 = 2*10 + 3%10

int hh = (h2 * 10 + h1 % 10);

//Get minutes

int m1 = (int)str[3] - '0';

int m2 = (int)str[4] - '0';

int mm = (m1 * 10 + m2 %10);

bool time_validate = validate_time(hh,mm);

//if user Enter input is input is invalid

try

{

if(!time_validate)

{

cout << " There is no such time as " << str;

TimeFormatMistake expe;

throw expe;

}

}

catch(TimeFormatMistake &tm)

{

cout <<" Exception is caught";

return;

}

//convert 24 hrs to 12 hrs format

if(hh > 12)

{

result_hrs = hh % 12;

result = std::to_string(result_hrs);

result += ":";

result += std::to_string(mm);

result += "PM";

}

cout << " That is the same as " << result <<" Again?(y/n)";

}

int main()

{

string str;

char choice ;

do

{

cout << " Enter time in 24-hour notation:";

cin>>str;

get_time_validate(str);

cin >> choice;

}while((choice == 'y'));

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote