views:

487

answers:

3

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, "");
+17  A: 

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.

akappa
Thanks for the clarification. I googled a bit but couldn't find the answer.
Aamir
I can't get this to work with sscanf
e5
+1  A: 

* 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.
jitter
A: 

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

pauldoo