If and else being executed simultaneously

Hi there, I'm very very new to C++ and I have an error that I cant figure out.
My code's purpose is to convert military time to 12 hour time.

However, when I type in something like 17:45:45

it both coverts it to 05:45:45 from the 2nd if statement, but also outputs the characters from the else statement.


int hour;
int min;
int sec;
cout<<"Enter a time value in the following format: HH MM SS"<<endl;

cin>>hour>>min>>sec;

int timechange= hour - 12;

if (hour>0 && hour<=12)
{
cout<<setfill('0')<<setw(2)<<hour<<":"<<setfill('0')<<setw(2)<<min<<":"<<setfill('0')<<setw(2)<<sec<<"AM"<<endl;
}

if (hour>12 && hour<=23)
{
cout<<setfill('0')<<setw(2)<<timechange<<":"<<setfill('0')<<setw(2)<<min<<":"<<setfill('0')<<setw(2)<<sec<<"PM"<<endl;
}

if (hour==0)
{
cout<<"12:"<<setfill('0')<<setw(2)<<min<<":"<<setfill('0')<<setw(2)<<sec<<"AM"<<endl;
}


else
{
cout<<"Hour must be between 0 and 23 inclusive."<<endl;
}


}


Any help? Sorry, i know im a noob.
I'm pretty new myself but I'm going to UAT for programming so I'll see if I can't help you out...

I'm not exactly sure why it would be both converting AND sending out the else statement. However, I think the reason it's not working properly is because the If... Else statement is only a double sort. If you'd like to have multiple selection statements, you should use nested if else. So your code would be

if (hour>0 && hour<=12)
{
cout<<setfill('0')<<setw(2)<<hour<<":"<<setfill('0')<<setw(2)<<min<<":"<<setfill('0')<<setw(2)<<sec<<"AM"<<endl;
}

else if (hour>12 && hour<=23)
{
cout<<setfill('0')<<setw(2)<<timechange<<":"<<setfill('0')<<setw(2)<<min<<":"<<setfill('0')<<setw(2)<<sec<<"PM"<<endl;
}

else if (hour==0)
{
cout<<"12:"<<setfill('0')<<setw(2)<<min<<":"<<setfill('0')<<setw(2)<<sec<<"AM"<<endl;
}

else
{
cout<<"Hour must be between 0 and 23 inclusive."<<endl;
}


}

Try that.
Your else statement is paired with your if (hour==0) statement.

An else statement will be carried out whenever the if statement it is paired with fails, so in this case, any time that the condition hour==0 is not true when you get to the final if statement, that else block will be run.

Topic archived. No new replies allowed.