New to C++ need some help with a time conversion question

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
using namespace 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;
}
else if (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
else if (minutes==0){ //Without this it will output 0 minutes as hours:0 instead of hours:00
    cout<<hours<<":00";
}

}
Last edited on
Well since the space between minutes and am/pm is optional, line 9 is wrong.

> I ended up having to make two seperate if statements for p and P because
Look up toupper and tolower in ctype.
Then you only need one comparison

if ( tolower(ampm) == 'p' )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <iomanip>
#include <string>
#include <cctype>
using namespace std;

int main ()
{
   int hours, minutes;
   string ampm;
   char colon;
   cout << "Enter time: ";
   cin >> hours >> colon >> minutes >> ampm;
   if ( tolower( ampm[0] ) == 'p' && hours != 12 ) hours += 12;
   if ( tolower( ampm[0] ) == 'a' && hours == 12 ) hours =   0;
   cout << setfill( '0' ) << setw( 2 ) << hours << ':' << setw( 2 ) << minutes << '\n';
}
Last edited on
Topic archived. No new replies allowed.