I am stuck on a homework problem where I have to convert 12 hours to 24 hours.
Prompt
This programs lets you practice using the String Processing Operations. You can also use cin where the data are in compressed form. Either approach is OK.
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. (The time must be entered exactly in this format all on one line.) 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 before AM/PM, or you may choose to use separate variables for the hours, minutes, seconds and AM/PM.
Run your program and show the output for each of the five examples below.
Examples:
Input (12HR) Output(24hr)
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:22
Here's a start to fixing it up with 2 variable name changes to make it a bit clearer.
<fstream> not needed, <iomanip> still needed to do formatting. Maybe also include checking to make sure input meets the spec - AM or PM only, seconds < 60 etc
One small problem.....
when I input 12:32:50 AM the output is 12:32:50 when it is supposed to be 00:32:50
Not entirely sure if that output my professor provided is true but it's driving me crazy.
its working as you told it to.
you entered 12 am.
is am == pm?
no, do not add 12.
there are fancy ways to do it but the simple one is just to say
if its pm or its am and hours is 12
which in c++ is
if(AMPM== "PM")
hours +=12;
else
if(hours == 12) //you know it is AM here, because its not PM, from the else.
hours = 0;
and its still not quite right.
what do you get for 12pm noon? 24..!
OP, can you fix that last bug on your own?
hint: if the hours are 12, and you already handled PM, a single condition will fix both cases by subtracting 12... (and any AM/12 specific code goes away or is modified into this fix).
--- advanced way ---
the simplest fix is just a %
hours%=12;
if(AMPM=="PM")
{
hours += 12;
}
//nothing after this, its all fixed up
you can even 1 line it..
hours %=12 + (AMPM==PM)*12; //this is just silly. bool is 1 or 0, so its 1*12 or 0 * 12 added.