Is this printf format possible (left-justify sign and no sign on zero)?

Viewed 636

I'm trying to use printf to get the following programmatic output:

- 20
- 15
- 10
-  5
   0
+  5
+ 10
+ 15
+ 20

The key specifications are:

  • The field width is always 4
  • The sign is always left-justified
  • The number is always right-justified
  • The zero has no sign

So far I have not been able to come up with a printf statement that will give me the desired results. The closest I have is:

for(int i = -20; i <= 20; i+=5)
{
    printf("%-+4d \n", i);
}

which produces:

-20
-15
-10
-5
+0
+5
+10
+15
+20

Is there a way to do this without having to do any cumbersome string manipulation?

4 Answers
Related