I am going through some code where I got stuck reading a printf statement:
printf("%*s%s\n", stat[type].dent, "", buf);
states[type].indent
is a number which is equal to 4 and buf
is buffer of 215 bytes with 0 strored into it as string but not sure ""
and %*s
is meant for.
Can anybody help me reading this printf
statement?
The *
in the format code "%*s"
tells printf
that the next argument is a field width followed by the normal argument (a string in this case).
It's the same as eg "%4s"
in your case, but the width can be set in runtime.
So here stat[type].dent
is the field width, and the empty string is the string. So this prints the empty string with 4 characters width (so you get four spaces) followed by whatever is in buf
.
I recommend a good reference on printf
where it's all documented.
The *
means that the width of the argument to be printed is dependent on an (integer) argument that precedes it.
From cplusplus :
printf ("Width trick: %*d \n", 5, 10); // 5 is the width, 10 is the integer being printed
The %*s
is a string conversion. The *
part means that a width for the field will be supplied as a parameter (that's how stat[type].dent
is used). So it's printing an empty string in some specified width (call it N). In other words, its leaves N blank spaces before printing out buf
.
*
将被stat[type].dent
的值代替,该值是一个数字,称为最小字段宽度。
It is a precision, which specifies maximum number of bytes for string conversions.
Asterisk (*), uses an integer argument, which specifies the value (for precision) to be used.
To print a string for a variable length,specify printf("%*s", l, string)
. The l
is substituted for the asterisk.
"%*s%s\\n"
is a format that contains 3 directives .
"%*s"
This directive is the string conversion specification. The *
causes the field width, an int
, to be determined from the the next parameter after the format. As OP mentions, this is the value of 4 from stat[type].dent
. The s
conversion specification then gets the next parameter ( ""
) and treats it a pointer to char *
, which it is. Thus printf()
prints out ""
, pre-padding first with spaces, up to 4, as needed. 4 padding spaces are needed here as the string length of ""
is 0. Net result: 4 spaces printed.
"%s"
This directive, also a string conversion specification, takes the next parameter, buf
, assumes it is a char *
, which it is, and prints its contents out. Unclear if OP means it is all 0, if so, then nothing is printed.
"\\n"
This final directive is simply a text, so "\\n"
is printed.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.