Search code examples
cprintfformat-specifiers

About printf format string in C


Let's take the following program:

#include <stdio.h>

int main()
{
    long t =57 ;
    printf("[%+03ld]", t);
}

and it's output:

[+57]

I am somehow confused: I told him to pad the output to width 3 (03ld), with zeroes, however it seems that if I force the output to put a plus sign before the number (+) it will not add the required zeroes if the length of the number is already 2 digits (as in 57). For numbers <10 it pads with 1 zero.

From http://www.cplusplus.com/reference/cstdio/printf/

(0) -> Left-pads the number with zeroes (0) instead of spaces when padding is specified (see width sub-specifier).

(+) -> Forces to preceed the result with a plus or minus sign (+ or -) even for positive numbers. By default, only negative numbers are preceded with a - sign.

(width) -> Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger.

So I just need a clarification ... The (width) specifier from the quote above refers to the full length of the output string (ie: the characters that will be printed) controlled by this format specifier ("%+03ld") or the full length of the characters of the number that is going to be printed?


Solution

  • Yes, the width specifier refers to the width of the entire formatted result, +57 in your case. This makes it useful for printing columnar text for easy reading on screen (important if you're using C to write an old-school text utility!).