Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print a leading '+' for positive numbers in printf

I've a temperature conversion program as an assignment, which I've completed. The program has many printf statements in it which print the temperature. Now the negative temperatures are printed the way I want them but the positive temperatures are printed without a leading + sign.

Now what is the best way to get printf print a leading +sign for positive number. All I could think of is to change

printf("Min temp = %d\n",max_temp) 

to

if(max_temp > 0)     printf("+"); printf("Min temp = %d\n",max_temp) 

But that calls for many changes in program :(

Another option is to write my own print function and put this logic there. What do you suggest ?

like image 490
user292844 Avatar asked Aug 28 '10 02:08

user292844


People also ask

What does %% do in printf?

It is an escape sequence. As % has special meaning in printf type functions, to print the literal %, you type %% to prevent it from being interpreted as starting a conversion fmt.

What is %B in printf?

The Printf module API details the type conversion flags, among them: %B: convert a boolean argument to the string true or false %b: convert a boolean argument (deprecated; do not use in new programs).


1 Answers

You can use the + flag of printf to print positive numbers with a leading + sign as:

printf("%+d %+d",10,-10); // prints +10 -10 
like image 180
codaddict Avatar answered Sep 18 '22 22:09

codaddict