This program converts a 24-Hour Format time to the normal time. The argument sho
ID: 3631170 • Letter: T
Question
This program converts a 24-Hour Format time to the normal time. The argument should be a C++ string in "HH:MM" 24-hour format. The result will be a C++ string written as "HH:MM AM" or "HH:MM PM" in 12-hour format with AM or PM. The following is the function suggested to receive a 24-hour time and return the converted 12-hour time.string GetTimeFrom24HourFormat(const string& time);
=============================================================================
Using C++ string is required, not using C-string. A program can be run like this:
Enter a time 'HH:MM' in 24-Hour-Format: 11:02
11:02 is converted to 11:02 AM
Try Again? (y/n) y
Enter a time 'HH:MM' in 24-Hour-Format: 12:30
12:30 is converted to 12:30 PM
Try Again? (y/n) y
Enter a time 'HH:MM' in 24-Hour-Format: 15:22
15:22 is converted to 03:22 PM
Try Again? (y/n) y
Enter a time 'HH:MM' in 24-Hour-Format: 00:20
24:00 is converted to 12:20 AM
Try Again? (y/n)
Explanation / Answer
#include<iostream>
#include<sstream>
using namespace std;
string GetTimeFrom24HourFormat(const string& time)
{
string ans="";
int am=1;
int numb;
stringstream ss;
ss << time.substr(0,2);
stringstream ss1;
ss >> numb;
if(numb > 12)
{
ss1 <<numb%12;
ans.append(ss1.str());
am = 0;
}
else
{
ss1 <<numb;
ans.append(ss1.str());
}
ans.append(":");
ans.append(time.substr(3,4));
ans.append(" ");
if(am)
ans.append("AM");
else
ans.append("PM");
return ans;
}
int main()
{
string time=;
char c;
do
{
cout << " Enter a time 'HH:MM' in 24-Hour-Format: 11:02" ;
cin >> time;
cout << time << " is converted to " << GetTimeFrom24HourFormat(time);
cout << "Try Again? (y/n)";
cin >> c;
}while(c=='y');
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.