In: Computer Science
home / study / engineering / computer science / computer science questions and answers / instructions write a program to convert the time from 24-hour notation to 12-hour notation ...
Question: Instructions Write a program to convert the time from 24-hour notation to 12-hour notation and vi...
Instructions
Write a program to convert the time from 24-hour notation to 12-hour notation and vice versa. Your program must be menu driven, giving the user the choice of converting the time between the two notations.
Furthermore, your program must contain at least the following functions:
(Please do rate the answer if you found useful - read comments for explanation - output is also attached )
Program Code:
#include <iostream>
#include <string>
using namespace std;
string inputstr() {
string st;
cout<<"Enter Time in hh:mm:ss AM or hh:mm:ss PM
format:\n";
cin>>st;
return st;
}
string inputstr2() {
string st;
cout<<"Enter Time in hh:mm:ss :\n";
cin>>st;
return st;
}
int twentyfour(string str)
{
// compute hours
int hour1 = (int)str[1] - '0';
int hour2 = (int)str[0] - '0';
int hh = (hour2 * 10 + hour1 % 10);
return hh;
}
int twelve(string str) {
// compute hours
int hour1 = (int)str[0] - '0';
int hour2 = (int)str[1] - '0';
int hh = hour1 * 10 + hour2;
return hh;
}
void disp1(int hh,string str) {
// code block to convert time in AM to 24hrs
if (str[8] == 'A')
{
if (hh == 12)
{
cout << "00";
for (int i=2; i <= 7; i++)
cout << str[i];
}
else
{
for (int i=0; i <= 7; i++)
cout << str[i];
}
}
// Code block to convert time in PM to 24hrs
else
{
if (hh == 12)
{
cout << "12";
for (int i=2; i <= 7; i++)
cout << str[i];
}
else
{
hh = hh + 12;
cout << hh;
for (int i=2; i <= 7; i++)
cout << str[i];
}
}
cout<<"\n";
}
void disp2(int hh,string str) {
// Finding/Determining whether time is in AM or PM
string Mr;
if (hh < 12) {
Mr = "AM";
}
else
Mr = "PM";
hh %= 12;
// Handle 00 and 12 case separately
if (hh == 0) {
cout << "12";
// Display minutes and seconds
for (int i = 2; i < 8; ++i) {
cout << str[i];
}
}
else {
cout << hh;
// Display minutes and seconds
for (int i = 2; i < 8; ++i) {
cout << str[i];
}
}
//Used to print AM or PM after Time
cout << " " << Mr << '\n';
}
int main()
{ string str;
int ch;
int hh;
while(1) {
cout<<"\n1: 12-hour notation to 24-hour notation\n";
cout<<"2: 24-hour notation to 12-hour notation\n";
cout<<"3: Exit\n";
cout<<"Enter your choice: ";
cin>>ch;
switch(ch) {
case 1: str=inputstr();
hh= twentyfour(str);
disp1(hh,str);
break;
case 2:str=inputstr2();
hh=twelve(str);
disp2(hh,str);
break;
case 3: exit(0);break;
default: cout<<"Wrong Choice";
}
}
return 0;
}
Output: