About printf format string in C

Let's take the following program:

#include <stdio.h>

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


and outputs:



I'm kind of confused: I told him to overlay the output to a width of 3 ( 03ld

) with zeros, however it seems that if I force the output to put a plus sign in front of the number ( +

), it won't add zero zeros if the number is already 2 digits long (as in 57). For numbers <10, it contains 1 zero.

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

(0) โ†’ Stops a number with zeros (0) instead of spaces when padding is given (see width specifier).

(+) โ†’ Forcibly exceed the result with a plus or minus sign (+ or -) even for positive numbers. By default, only negative numbers are preceded by an a.

(width) โ†’ Minimum number of characters to print. If the value to be printed is less than this number, the result will be filled with spaces. The value is not truncated even if the result is larger.

So I just need clarification ... Does the specifier (width)

from the above quote refer to the full length of the output string (i.e.: characters to be printed) controlled by that format specifier ( "%+03ld"

), or the full character length of the number to be printed?


source to share

5 answers

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 readability on the screen (important if you're using C for writing an old-school text utility!).




C is pretty accurate that the converted value is taken as an integer. From C11 ยง7.21.6 / 2 (emphasis mine):

The function fprintf

writes output to stream

, pointed to stream

, controlled by the string pointed to by the format, which determines how subsequent arguments are converted for output .

together with ยง7.21.6 / 4:

Optional minimum field width. If the converted value is less characters than the field width, it is padded with spaces (by default) to the left (or right if the left adjustment checkbox described below)) to the field width. The field width takes the form of an asterisk * (described below) or a non-negative decimal integer.



As you pointed out "Minimum number of characters to print", so "+" is another character for printf. By the way, the zeros "0" are just characters and have nothing to do with numbers. It can be any character.



Yes, the field width refers to the full, converted value, including decimal points, signs, etc.



You asked for a 3 character length format and got 3 characters +57

. If you want 0 to be present, just use printf("[%+04ld]", t);

and you get +057




All Articles