Program 3. Write a program that converts a time in 12-hour format to 24-hour for
ID: 3742279 • Letter: P
Question
Program 3. Write a program that converts a time in 12-hour format to 24-hour format. The program will prompt the user to enter a time in HH:MM:SS AM/PM form. It will then convert the time to 24 hour form. You may use a string type to read in the entire time at once including the space or you may choose to use separate variables for the hours, minutes, seconds and AM/PM. Show output for each of the examples below. Examples: Output Input AM/PM24-Hour 5:30:00 PM 17:30:00 6:45:50 AM 06:45:50 12:32:30 AM 00:32:30 12:15:18 PM 12:15:18 1:02:22 PM 13:02:22Explanation / Answer
// C++ program to convert 12 hour to 24 hour
// format
#include<iostream>
using namespace std;
void print24(string str)
{
// Get hours
int h1 = (int)str[1] - '0';
int h2 = (int)str[0] - '0';
int hh = (h2 * 10 + h1 % 10);
// If time is in "AM"
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];
}
}
// If time is in "PM"
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];
}
}
}
// Driver code
int main()
{
string str = "05:30:00PM";// here you can giver your own time in 12 hours format...//
print24(str);
return 0;
}
-----------------------------------------------
note:in input you can give what time you want .....
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.