printf format align
Understanding %-*.*s in C
🧩 The general form
| |
So %-*.*s combines several parts:
| Part | Meaning |
|---|---|
| % | 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” |
| s | print 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
| |
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:
| |
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