Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

printf

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.

like image 979
Matra Avatar asked Mar 13 '23 21:03

Matra


1 Answers

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);

;-)

like image 198
alk Avatar answered Mar 24 '23 13:03

alk