Matra
Matra

Reputation: 51

Changing text in printf() based on value of a variable

I haven't done C in a long while and slowly getting back into it. I made a small game and now going through 'bug-fixing' and making the odd tweak here and there. One issue I have if the text inside a printf() statement regarding turns ...

printf("CONGRATULATIONS!!\nYou won with %d turns remaining\n",turns);

Now that is great until turns==1.

Is there an efficient way to change the text 'turns' based on the condition of the turns variable? Or would I have to use if statements (one solution I already have but I'm sure there is a better one!)

if (turns==1)
{
  printf("CONGRATULATIONS!!\nYou won with %d turn remaining\n",turns);
}
else
{
  printf("CONGRATULATIONS!!\nYou won with %d turns remaining\n",turns);
}

Sorry for the really 'noob' question but I'm stuck as to what would be the most efficient way of doing this.

Upvotes: 4

Views: 222

Answers (1)

alk
alk

Reputation: 70931

Using the conditional-operator might satisfy your needs

printf("CONGRATULATIONS!!\nYou won with %d turn%s remaining.\n", 
  turns, 
  turns==1 ?"" :"s");

or just do

printf("CONGRATULATIONS!!\nYou won with %d turn(s) remaining.\n",
  turns);

;-)

Upvotes: 7

Related Questions