3

How can I achieve fixed length padding with trailing spaces by using sprintf?

For example, how can I get sprintf(buf, "The number is:%i", n) to output 50 characters with trailing spaces?

6
  • Did you read man 3 printf (on Unix)? Put "printf" in the search engine of your choice? Commented Dec 18, 2015 at 2:51
  • Yes I did search and had no luck. The problem is that, I want fixed total length rather than partially fixed. Such as %10i formatting can only fix the number, it doesn't help anything about the total length. Commented Dec 18, 2015 at 9:44
  • So you don't want 50 trailing spaces, but you want the whole output to be 50 characters? Commented Dec 18, 2015 at 15:37
  • Yes! Thanks for your downstairs reply. Actually I had the same workaround as your post. However my initial thought is to find if there would be a solution with only formatting string. Commented Dec 18, 2015 at 18:47
  • Well, you could have added that to your question and saved me the work... Commented Dec 18, 2015 at 21:03

1 Answer 1

4

My man 3 printf says:

An optional decimal digit string specifying a minimum field width. If the converted value has fewer characters than the field width, it will be padded with spaces on the left (or right, if the left-adjustment flag has been given) to fill out the field width.

and

`-' A negative field width flag; the converted value is to be left adjusted on the field boundary. Except for n conver- sions, the converted value is padded on the right with blanks, rather than on the left with blanks or zeros. A - overrides a 0 if both are given.

and

A field width or precision, or both, may be indicated by an asterisk '*' or an asterisk followed by one or more decimal digits and a '$' instead of a digit string. In this case, an int argument supplies the field width or precision.

So I tried:

#include <stdio.h>
#include <string.h>

int main() {
    int num = 123;
    char* text = "The number is: ";
    printf("%s%-*iX\n", text, 50 - (int) strlen(text), num);
}

That gets:

The number is: 123                                X

(Where the X is just a marker to show the spaces for padding.)

Sign up to request clarification or add additional context in comments.

1 Comment

Fantastic answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.