My ternary operator

I don't think I'm understanding how this works.

1
2
3
4
5
6
7

int diceTotal = diceDisplay() + diceDisplay(); //combine total of both dice

cout << "You got: " << diceTotal << endl; //display result to the user

cout << (diceTotal == 7) ? "Natural" : "Yo-Leven";


I want Natural to be displayed when diceTotal is 7 and YoLeven when diceTotal is 11.
Then the ternary operator is inappropriate.
What you're saying now (translating the ternary operator to an if-else):
1
2
3
4
5
6
7
8
if (diceTotal == 7)
{
    cout << "Natural";
}
else
{
    cout << "Yo-Leven";
}

What you want to say:
1
2
3
4
5
6
7
8
if (diceTotal == 7)
{
    cout << "Natural";
}
else if (diceTotal == 11)
{
    cout << "Yo-Leven";
}


If you want difficult-to-read, punishable-by-flogging code, chain multiple ternary operators together. :)
cout << (diceTotal == 7) ? "Natural" : ((diceTotal == 11) ? "Yo-Leven" : "");
Last edited on
Topic archived. No new replies allowed.