Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
687 views
in Technique[技术] by (71.8m points)

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

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...