Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 636
Ferenc Deak Avatar asked Feb 02 '26 04:02

Ferenc Deak


2 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 easy reading on screen (important if you're using C to write an old-school text utility!).

like image 168
John Zwinck Avatar answered Feb 04 '26 23:02

John Zwinck


C standard is rather precise that converted value is taken a whole. From C11 §7.21.6/2 (emphasis mine):

The fprintf function writes output to the stream pointed to by stream, under control of the string pointed to by format that specifies how subsequent arguments are converted for output.

along with §7.21.6/4:

An optional minimum field width. If the converted value has fewer characters than the field width, it is padded with spaces (by default) on the left (or right, if the left adjustment flag, described later, has been given) to the field width. The field width takes the form of an asterisk * (described later) or a nonnegative decimal integer.

like image 22
Grzegorz Szpetkowski Avatar answered Feb 04 '26 23:02

Grzegorz Szpetkowski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!