Question
24-hour time (also known in the U.S. as military time) is widelyused around the world. Time is expressed as hours since midnight.The day starts at
24-hour time (also known in the U.S. as military time) is widelyused around the world. Time is expressed as hours since midnight.The day starts at 0000, and ends at 2359. Write a program thatconverts am/pm time to 24-hour time. If the input is 2:30 pm, theoutput should be 1430. If the input is 12:01 am, the output shouldbe 0001.
Hints:
Think of how each hour should be handled. 12:00 am -12:59 ambecomes what? 8:00 am becomes what? 12:00 pm? 1:00 pm? Group thehours into cases that should be handled similarly (e.g., 1:00 am to11:00 am are handled the same).
Declare variables for hoursAmPm, minAmPm, and hours24. Note thatminutes for 24-hour time remain the same as for am/pm, so no extravariable is needed.
Use an if-else statement to detect each case, and set thehours24 appropriately.
When outputting hour24, check if the hour is 0-9 (just check for< 10). If so, output a "0". So 7 will be output as 07. Do thesame when outputting the minutes
#include
#include
using namespace std;
int convertStringToInt(string str)
{
stringstream s(str);
int result = 0;
s>>result;
return result;
}
int main()
{
string hoursAmPm,minAmPm,am_pm, hour;
int hour24, min24;
cin>>hoursAmPm>>minAmPm>>am_pm;
if(am_pm == "am")
{// am_pm = "am"
if(hoursAmPm == "12")
hour = "0";
else if(hoursAmPm == "1")
hour = "1";
else if(hoursAmPm == "2")
hour = "2";
else if(hoursAmPm == "3")
hour = "3";
else if(hoursAmPm == "4")
hour = "4";
else if(hoursAmPm == "5")
hour = "5";
else if(hoursAmPm == "6")
hour = "6";
else if(hoursAmPm == "7")
hour = "7";
else if(hoursAmPm == "8")
hour = "8";
else if(hoursAmPm == "9")
hour = "9";
else if(hoursAmPm == "10")
hour = "10";
else if(hoursAmPm == "11")
hour = "11";
}
else
{// am_pm = "pm"
if(hoursAmPm == "12")
hour = "12";
else if(hoursAmPm == "1")
hour = "13";
else if(hoursAmPm == "2")
hour = "14";
else if(hoursAmPm == "3")
hour = "15";
else if(hoursAmPm == "4")
hour = "16";
else if(hoursAmPm == "5")
hour = "17";
else if(hoursAmPm == "6")
hour = "18";
else if(hoursAmPm == "7")
hour = "19";
else if(hoursAmPm == "8")
hour = "20";
else if(hoursAmPm == "9")
hour = "21";
else if(hoursAmPm == "10")
hour = "22";
else if(hoursAmPm == "11")
hour = "23";
}
hour24 = convertStringToInt(hour);
min24 = convertStringToInt(minAmPm);
if(hour24<10)
cout<<"0"<
else
cout<
if(min24 < 10)
cout<<"0"<
else
cout<
return 0;
}
if I input 12 01 am then it's working but i want to input 12:01am it's doesn't work can you help me with this??
Thanks!!!!!
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started