Write a program that inputs a time from the console. The time should be in the format “HH:MM AM” or “HH:MM PM”. Hours may be one or two digits, for example, “1:10 AM” or “11:30 PM”. Your program should then convert the time into a four digit military time based on a 24 hour clock. For example, “1:10 AM” would output “0110 hours” and “12:30 PM” would output “2330 hours”.
c++Code:
#include<iostream>
#include<string.h>
#include<cstdlib>
using namespace std;
int main()
{
string t;
cout<<"Enter time in (HH:MM AM) or (HH:MM PM) format:";
getline(cin,t,'n');
int col=t.find(":");
int spc=t.find(" ");
string h=t.substr(0,col);
string m=t.substr(col+1,spc-col-1);
string mer=t.substr(spc+1);
int hrs=atoi(h.c_str());
if(mer=="PM" && hrs!=12)
hrs=hrs+12;
else if(mer=="AM" && hrs==12)
hrs=0;
if(hrs>=0 && hrs<=9)
h="0";
else
h="";
char H[5];
h+=itoa(hrs,H,10);
result=h+m+"hours";
cout<<result;
return 0;
}
Get Answers For Free
Most questions answered within 1 hours.