Hi can someone help in in understanding the following code esp the "?".I cant understand how the output 9:10:5 as obtained.
Thank You.
The code is as followed:

``````#include <iostream>
using namespace std;

int main()
{

short  hour =9, minute =10, second =5;
cout << (hour <10 ? "0":"" )<<hour<<":"
<< (minute <10 ? "0":"" )<<minute<<":"
<< (second <10 ? "0":"" )<<second<<endl;

cin.get();

return 0;
}``````

## Recommended Answers

It's simple. Just break them into segments.
hour < 10 ? "0" : " "
The hour <10 part tells that if value of hour is less than 10 then 0 will be displayed, if hour is not less than 10 then it displays nothing.
If the condition is satisfied …

## All 3 Replies

It's simple. Just break them into segments.
hour < 10 ? "0" : " "
The hour <10 part tells that if value of hour is less than 10 then 0 will be displayed, if hour is not less than 10 then it displays nothing.
If the condition is satisfied then the expression following ? is done if the condition is not satisfied then the expression after : is done.

Use code tags

It is a conditional statement of the form [(boolean expression evaluation) ? (execution in case of true) : (execution in case of false)].Much like an if else statement.In this particular case if (hour<10) will evaluate to true a "0" will be inserted first in the cout stream and a "" otherwise.

I know you asked about the conditional operator, but the following is a more conventional way of adding leading zeros to a fixed field width:

``````#include <iomanip>
#include <iostream>

using namespace std;

int main()
{
short hour = 9;
short minute = 10;
short second = 5;

char last_fill = cout.fill('0');

cout << setw(2) << hour << ":"
<< setw(2) << minute << ":"
<< setw(2) << second << endl;

cout.fill(last_fill);
}``````
Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.