Thompson
Thompson

Reputation: 493

What is the meaning of "%-*.*s" in a printf format string?

#define FMT "%-*.*s e = %6ld, chars = %7ld, stat = %3u: %c %c %c %c\n"

This macro is passed into the printf function. What does %-*.*s mean?

Upvotes: 22

Views: 51409

Answers (1)

Peter - Reinstate Monica
Peter - Reinstate Monica

Reputation: 16026

You can read the manual page for printf. But it's more like a law text than a tutorial, so it will be hard to understand.

I didn't know *.* and had to read the man page myself. It's interesting. Let's start with a simple printf("%s", "abc"). It will print the string abc.

printf("%8s", "abc") will print abc, including 5 leading spaces: 8 is the "field width". Think of a table of data with column widths so that data in the same column is vertically aligned. The data is by default right-aligned, suitable for numbers.

printf("%-8s", "abc") will print abc , including 5 trailing spaces: the minus indicates left alignment in the field.

It is important that this is a minimum field width: In spite of the field width being only 8, printf("%-8s", "1234567890") will print all 10 characters, without any spaces.

Now for the star: printf("%-*s", 8, "abc") will print the same as the ordinary printf("%-8s", "abc"). The star indicates that the field width (here: 8) will be passed as a parameter to printf. That way it can be changed programmatically.1

Now for the "precision", that is: printf("%-*.10s", 8, "1234567890123") will print only 1234567890, omitting the last three characters: the "precision" is the maximum field width in case of strings. This is one of the rare cases (apart from rounding, which is also controlled by the precision value) where data is truncated by printf.

And finally printf("%-*.*s", 8, 10, "1234567890123") will print the same as before, but the maximum field width is given as a parameter, too.


1It is also possible to pass a regular char pointer as a format string, instead of a string literal. That pointer can point to a buffer where a format string has been composed at runtime, for example with ssprintf, allowing for even more runtime flexibility. This is pretty rare, partly owing to the fact that the actual parameters to printf are fixed at compile time, which mostly determines the conversion specifiers at compile time as well. Most likely, it is just the field width that is undetermined at compile time.

Upvotes: 68

Related Questions