My assignment has the question "Create a program that will ask users for a 12-hour time, then shows the time in 24-hour
form:
Enter a 12 hour-time: 9:11 PM
Equivalent 24-hour time: 21:11
Enter a 12 hour-time: 9:01a
Equivalent 24-hour time: 9:01
Notice that there can be a white space allowed (but not required) between the number and
AM/PM indicator (In addition, lowercase case letter, and indicator such as A, P, are also
allowed)"
My code bellow works fine except it doesnt work when I input the time like "9:01a" or "9:01P" any help would be appreciated.
#include <iostream>
usingnamespace std;
int main (){
int hours, minutes;
char ampm;
cin>>hours;
cin.ignore();
cin>>minutes;
cin.ignore();
cin.get(ampm);
if (ampm=='a'){
if (hours==12){hours-=12;}
}
if (ampm=='A'){
if (hours==12){hours-=12;}
}
if (ampm=='p'){ //Checks if its PM it still works if you enter PM instead of p/P
if (hours<12){
hours+=12;
}
}
if (ampm=='P'){ //I ended up having to make two seperate if statements for p and P because if I put it in one a char is
//either not equal to 'a', or it is equal to 'p', in which case it's not equal to 'P', so this condition is always true.
if (hours<12){
hours+=12;
}
}
if (minutes>0){
cout<<hours<<":"<<minutes;
}
elseif (hours==0 && minutes==0){cout<<hours<<":00 or 24:00";} //To indicate that 12:00 AM in a 24 hours clock is either 0:00 or 24:00
elseif (minutes==0){ //Without this it will output 0 minutes as hours:0 instead of hours:00
cout<<hours<<":00";
}
}