tags:

views:

82

answers:

3

While reading about printf(),I found that it can print numbers as positive or negative as desired by the user by following code(for -).But the code doesnt work and the output is a positive value.Please mention where the error is.Thanks

#include<stdio.h>
int main()
{
  printf (" %-d\n", 1977);
  return 0;
}
+4  A: 

%-d Will left adjust the integer field, it won't flip the sign. Do this instead:

printf (" %d\n", -1977);

Here's the full extract from print(3) under The flag characters:

       -      The  converted  value is to be left adjusted on the field bound‐
              ary.  (The default is right justification.)  Except for  n  con‐
              versions,  the  converted  value  is  padded  on  the right with
              blanks, rather than on the left with blanks or zeros.  A - over‐
              rides a 0 if both are given.

Update0

I see your true question now: To prepend output with the appropriate sign, use the + flag character to explictly show the sign. Again here is the extract:

       +      A sign (+ or -) should always be placed before a number produced
              by a signed conversion.  By default a sign is used only for neg‐
              ative numbers.  A + overrides a space if both are used.

And use it like this (The command line printf is mostly identical):

matt@stanley:~/cpfs$ printf "%+d\n" 3
+3
matt@stanley:~/cpfs$ printf "%+d\n" -3
-3
matt@stanley:~/cpfs$ printf "%+u\n" -3
18446744073709551613

Be aware that explicitly requesting the sign won't imply treatment of the corresponding integer as signed as in the %u example above.

Matt Joiner
+3  A: 

printf (" -%d\n", 1977); will output -1997 (bad way to do it), if you would like negative numbers to become positive, do printf (" %d\n", -1 * 1977); (good way to do it)

read the reference for an idea of how format specifiers work

Alexander
the refrence says:Forces to precede the result with a plus or minus sign (+ or -) even for positive numbers. By default, only negative numbers are preceded with a - sign.
fahad
The reference says that for the PLUS sign.
Matt Kane
+4  A: 

From your comments it looks like you misread this page. The - and + specifiers do two completely different things, and neither does what you think '-' should do.

As others have noted, - does left justification. The + specifier prints positive numbers with a leading plus sign (and negative numbers still get a leading minus sign):

printf("%d %d %+d %+d\n", -10, 10, -10, 10);

outputs:

-10 10 -10 +10

schot
Oh!You it forces the compiler to SHOW the sign
fahad