Can someone help me write this program? Write a program that converts from the 2
ID: 3596251 • Letter: C
Question
Can someone help me write this program?
Write a program that converts from the 24-hour time format to the 12-hour time format. The following is a sample dialogue (user input is underlined):
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:65
That is not a valid time
Try again:
10:35
That is the same as
10:35 AM
Again? (y/n)
N
End of program
Define an exception class called TimeFormatException so that if the user enters an illegal time, like 10:65, your program will throw, catch, and handle a TimeFormatException exception. Your program should also be able to handle an appropriate exception for gibberish entries, like &&*68, and so on.
You should create a project, named Project4 and the project should contain all the relevant classes for this application.
Your program should be well documented and in particular, begin with a series of comments specifying:
a brief description of what the program does.
Explanation / Answer
#include<iostream>
#include<stdlib.h>
#include<string>
#include<iomanip>
#include<vector>
using namespace std;
int main(){
int hr,min,t,f=0;
char loop = 'y';
char time[6];
while(loop == 'y' || loop == 'Y'){
f=0;
cout<<"Enter time in 24-hour notation:"<<endl;
cin>>time;
hr = time[0] - '0';
t = time[1] - '0';
if(t >= 0 && t <= 9){
hr = hr*10 + time[1] - '0';
f=1;
}
if( hr >= 12 && hr < 24){
if(hr == 12){
cout<<"12:";
}else{
cout<<abs(hr-12)<<":";
}
if(f == 1){
min = time[3] - '0';
if(time[4] != '')
min = min*10 + time[4] - '0';
}else{
min = time[2] - '0';
if(time[3] != '')
min = min*10 + time[3] - '0';
}
if(min > 0 && min < 60){
cout<<setfill('0')<<setw(2)<<min<<" PM"<<endl;
}else{
cout<<"Time is not a valid time"<<endl;
}
}else if(hr < 12 && hr > 0){
if(f == 1){
min = time[3] - '0';
if(time[4] != '')
min = min*10 + time[4] - '0';
}else{
min = time[2] - '0';
if(time[3] != '')
min = min*10 + time[3] - '0';
}
if(min > 0 && min < 60){
cout<<setfill('0')<<setw(2)<<min<<" AM"<<endl;
}else{
cout<<"Time is not a valid time"<<endl;
}
}else if(hr == 24){
if(f == 1){
min = time[3] - '0';
if(time[4] != '')
min = min*10 + time[4] - '0';
}else{
min = time[2] - '0';
if(time[3] != '')
min = min*10 + time[3] - '0';
}
if(min > 0 && min < 60){
cout<<"00:"<<setfill('0')<<setw(2)<<min<<" AM"<<endl;
}else{
cout<<"Time is not a valid time"<<endl;
}
}else{
cout<<"Time is not a valid time"<<endl;
}
cout<<"Again? (y/n)"<<endl;
cin>>loop;
}
return 0;
}