About printf format string in C

和自甴很熟 提交于 2020-01-03 19:00:56

问题


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?


回答1:


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!).




回答2:


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.




回答3:


As you quoted "Minimum number of characters to be printed.", so "+" is just another character for printf. Btw the zeros "0" are just characters aswell and have nothing to do with numbers. It could be any character.




回答4:


Yes, the field width refers to the complete, converted value including decimal dots, signs etc.




回答5:


You asked for a 3 characters length format and get 3 characters +57. If you want the 0 to be present, just use printf("[%+04ld]", t); and you'll get +057.



来源:https://stackoverflow.com/questions/26273607/about-printf-format-string-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!