Need help with if statements inside a function

I've got this program to prompt for current time in 24 hour format. I use functions to convert the time and print in 12 hour format. The problem is with my convertTime24to12 function. When I build it for some reason if the time in higher than 13:00 it outputs as am instead of pm. looking at my if statements that shouldn't be the case and I'm pretty confused.

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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
 #include <iostream>
#include <string>

using namespace std;

//function prototyping
void getTime24(int& hour, char& ch, int& minutes);
void convertTime24to12(int& hour12, char& a);
void printTime24(int hour, char ch,int minutes);
void printTime12(int hour,char ch,int minutes);
char userWantsToContinue(char ans);

void main()
{
int hour=0;
char ch;
int minutes=0;

getTime24(hour, ch, minutes);
printTime24(hour,ch,minutes);
printTime12(hour, ch, minutes);
}

void getTime24(int& hour, char& ch, int& minutes)
{
cout << "Enter a time in 24 hour format (for example 13:45): ";
cin >> hour >> ch >> minutes; 

	while (hour < 0 || hour >= 24 || minutes < 0 || minutes >= 60) 
	{
		cout << "I'm sorry the information you entered is not valid. Please try again " << endl;
		cin >> hour >> ch >> minutes; 
	}
}

void convertTime24to12(int& hour12, char& a)
{
	if (hour12 >= 13)
	{
		hour12 = hour12 - 12;
		a = 'p';
	}

	if (hour12==12)
	{
		a='p';
	}
	
	if (hour12==0)
	{
		hour12=hour12+12;
		a= 'a';
	}

	if (hour12>=1 && hour12 <=11)
		a='a';
}

void printTime24(int hour,char ch,int minutes)
{
	cout << "That time in 24 hour format is: " << hour << ch << minutes<<endl;
}

void printTime12(int hour,char ch, int minutes)
{
	convertTime24to12(hour, ch);
	cout << "That time in 12 hour format is: " << hour <<":"<<minutes<<" "<<ch<<"m"<<endl;
}
If hour12 starts off in the convert function as 13, line 40 will change hour12 to 1 and set a to p. Then in line 55, hour12 equaling 1 will meet the condition in this if statement, and a will get reset to a.

I'd make this an if else structure so that only one of the statements gets executed.
Thanks for the reply, I actually changed it to have a = 'p' before the statements and its working now after I changed it a little. Here's how I fixed it

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void convertTime24to12(int& hour12, char& a)
{
	a='p';

	if (hour12==0)
	{
		hour12=hour12+12;
		a= 'a';
	}

	if (hour12 >=1 && hour12 <=11)
	{
		a= 'a';
	}

	if (hour12 >= 13)
	{
		hour12 = hour12 - 12;
	}
}
Topic archived. No new replies allowed.