printf format align

Understanding %-*.*s in C

🧩 The general form

1
%[flags][width][.precision][length]specifier

So %-*.*s combines several parts:

PartMeaning
%start of a format specifier
-left-justify the output (pad on the right with spaces)
*means “take the width value from an argument”
.*means “take the precision value from an argument”
sprint a string (char *)

🧠 Putting it together: %-*.*s

This means:

Print a string (s), left-aligned (-), with a field width and precision both given as arguments (the * and .*).


📘 Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
#include <stdio.h>

int main(void) {
    char *str = "HelloWorld";

    // Syntax: printf("%-*.*s", width, precision, string);
    printf("|%-10.5s|\n", str);     // width=10, precision=5
    printf("|%-*.*s|\n", 10, 5, str); // same as above (dynamic)

    return 0;
}

Output:

|Hello     |
|Hello     |

Explanation:

  • Precision = 5 → print only 5 characters from "HelloWorld""Hello".
  • Width = 10 → total field width is 10 → pad with 5 spaces.
  • - flag → padding on the right, so "Hello " instead of " Hello".

🔧 Without the - flag

If you used %*.*s instead:

1
printf("|%*.*s|\n", 10, 5, str);

Output:

|     Hello|

Now it’s right-aligned.


✅ Summary

Specifier Description


%s print string %.Ns print at most N characters %*s width taken from argument %.*s precision taken from argument %-*.*s left-align, with dynamic width and precision