Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

printf

#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?

like image 823
Thompson Avatar asked May 21 '14 07:05

Thompson


People also ask

What is * * s format specifier in C?

Format specifiers in C are used to take inputs and print the output of a type. The symbol we use in every format specifier is %. Format specifiers tell the compiler about the type of data that must be given or input and the type of data that must be printed on the screen.

What is %- 5D in C?

Example: "%05d" will be "00123" after processing. - period followed by the second string of numbers specifies accuracy, i.e. maximum number of decimal places. Example: "%6.3f" will be "12.345" after processing, "%. 2f" will be "12.34" after processing.

What is printf * s in C?

%s tells printf that the corresponding argument is to be treated as a string (in C terms, a 0-terminated sequence of char ); the type of the corresponding argument must be char * . %d tells printf that the corresponding argument is to be treated as an integer value; the type of the corresponding argument must be int .

What does %% mean in printf?

Save this answer. Show activity on this post. % indicates a format escape sequence used for formatting the variables passed to printf() . So you have to escape it to print the % character.


1 Answers

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.

like image 78
Peter - Reinstate Monica Avatar answered Sep 21 '22 04:09

Peter - Reinstate Monica