38

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 ?

codaddict
  • 445,704
  • 82
  • 492
  • 529
user292844
  • 589
  • 2
  • 5
  • 7

3 Answers3

77

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

printf("%+d %+d",10,-10); // prints +10 -10
codaddict
  • 445,704
  • 82
  • 492
  • 529
24

Add the + flag. Here is an example.

int n;
printf("%+d", n);

(assuming n is an int - just replace %d for other numeric types)

shreddd
  • 10,975
  • 9
  • 33
  • 34
1

I reckon you meant to do the following thing,

double num1 = 1.;

// print num1 with leading "+";
printf("%s%lf\n",num1>0.?"+":"",num1);   // +1.000000
emanon
  • 11
  • 1