What does the %*s format specifier mean?

Go To StackoverFlow.com

39

In some code that I have to maintain, I have seen a format specifier %*s . Can anybody tell me what this is and why it is used?

An example of its usage is like:

fprintf(outFile, "\n%*s", indent, "");
2009-06-16 10:00
by Aamir


48

It's used to specify, in a dynamic way, what the width of the field is:

  • The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.

so "indent" specifies how much space to allocate for the string that follows it in the parameter list.

So,

printf("%*s", 5, "");

is the same as

printf("%5s", "");

It's a nice way to put some spaces in your file, avoiding a loop.

2009-06-16 10:04
by akappa
Thanks for the clarification. I googled a bit but couldn't find the answer - Aamir 2009-06-16 10:11
I can't get this to work with sscan - Ethan Heilman 2010-01-24 03:32
@EthanHeilman, the * means something COMPLETELY different in the scanf family of functions - John Hascall 2014-09-06 20:56
Note that if you have a negative number, the field will be left justified. That is, printf("[%*s]\n", -10, "hello") will output "[hello     ]" rather than "[     hello]" which you would get if you use +10 (or 10) - Jonathan Leffler 2017-09-02 23:45


8

Don't use "%*s" on a buffer which is not NULL terminated (packed) thinking that it will print only "length" field.

2013-09-19 15:24
by user2132064
Use "%.*s" to achieve this - Andy G 2015-02-19 09:28


1

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

The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.

e.g: printf("%*s", 4, myValue); is equivelant to printf("%4s", myValue);.

2009-06-16 10:08
by pauldoo


1

The format specifier %4s outputs a String in a field width of 4—that is, printf displays the value with at least 4 character positions.

If the value to be output is less than 4 character positions wide, the value is right justified in the field by default.

If the value is greater than 4 character positions wide, the field width expands to accommodate the appropriate number of characters.

To left justify the value, use a negative integer to specify the field width.

References: Java™ How To Program (Early Objects), Tenth Edition

2017-02-14 11:21
by Basheer AL-MOMANI


0

* Causes fprintf to pad the output until it is n characters wide, where n is an integer value stored in the a function argument just preceding that represented by the modified type.

printf("%*d", 5, 10) //will result in "10" being printed with a width of 5.
2009-06-16 10:07
by jitter
Ads