I have a structure:
Code:
struct Time {
int time;
int hour;
int second;
};
and I have 2 functions:
Code:
void printMilitary( const Time &t )
{
cout << ( t.hour < 10 ? "0" : "" ) << t.hour << ":"
<< ( t.minute < 10 ? "0" : "" ) << t.minute;
}
void printStandard( const Time &t )
{
cout << ( ( t.hour == 0 || t.hour == 12 ) ?
12 : t.hour % 12 )
<< ":" << ( t.minute < 10 ? "0" : "" ) << t.minute
<< ":" << ( t.second < 10 ? "0" : "" ) << t.second
<< ( t.hour < 12 ? " AM" : " PM" );
}
They are used like this:
Code:
int main()
{
Time dinnerTime;
dinnerTime.hour = 18;
dinnerTime.minute = 30;
dinnerTime.second = 0;
cout << "Dinner will be held at: ";
printMilitary( dinnerTime );
cout << " military time, \nwhich is ";
printStandard( dinnerTime );
cout << " standard time.\n";
What the code is doing, if you haven't already noticed, is taking military time format and displaying it as standard time format. My question is about the conditional operator ( ?: ). How is it taking the military time and converting it to standard time? If you really dont want to go into detail just comment the code I have listed.
Code:
cout << ( ( t.hour == 0 || t.hour == 12 ) ?
12 : t.hour % 12 )
<< ":" << ( t.minute < 10 ? "0" : "" ) << t.minute
<< ":" << ( t.second < 10 ? "0" : "" ) << t.second
<< ( t.hour < 12 ? " AM" : " PM" );