Issue
I have a number that may be negative or positive and I want it to pop out of sprintf() without the negative or positive sign. How would I do it?
I tried %d
% d
%- d
%+ d
% -d
% +d
and none of them work.
I tried gcc 4.8.2 and g++ 4.8.2 and it does not work. Is this a bug in gcc?
Solution
There is no format string that applies a absolute value functionality.
Here is what you have to do:
#include <stdio.h>
#include <math.h>
void main()
{
int num = -6000;
printf("%d\n", abs(num));
}
%d
will render 34 as34
and -34 as-34
.% d
will render 34 as (space) +34
and -34 as-34
.%+d
will render 34 as+34
and -34 as-34
."%5d
will render 34 as (three spaces) +34
and -34 as (two spaces) +-34
. They both will use the field size 5."%-5d
will render 34 as34
+ (three spaces) and -34 as-34
+ (two spaces). They both will use the field size 5, but left justified because of-
.
Answered By - Anders Lindén