0
What's wrong with my code?
3 Antworten
+ 1
Here is a list of some problems I found:
1) char arrays didn't have room for terminating NUL character.
2) input 12:00 AM not converted to 00:00 AM.
3) input 12:00 PM would result in 24:00 instead of 12:00.
4) hour output was not zero-filled to two digits.
Here is a cleaned up revision that passes all tests.
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int h;
char mm[3]; //leave room for NUL
char am[3]; //ditto
string time;
getline(cin, time);
sscanf(time.c_str(),"%d:%s %s",&h,mm,am);
h %= 12; //make 12 into 0
if(am[0]=='P')
h+=12;
cout<<setfill('0')<<setw(2)<<h<<":"<<mm;
return 0;
}
+ 1
Thank you
0
You want to convert the time from a 12 hour clock to a 24 hour clock. If you are given the time on a 12 hour clock, you should output the time as it would appear on a 24 hour clock.
Task:
Determine if the time you are given is AM or PM, then convert that value to the way that it would appear on a 24 hour clock.
Input Format:
A string that includes the time, then a space and the indicator for AM or PM.
Output Format:
A string that includes the time in a 24 hour format (XX:XX)
Sample Input:
1:15 PM
Sample Output:
13:15