Search code examples
cprintfstring-formattingformat-specifiers

How to use format specifiers to set field width of a string?


printf("%5s\n", "#");

gives:

    #

Is their a way to set field width of this string using an integer format specifier?

Something like this,

printf("%%ds\n", 5, "#");

Solution

  • From the printf manual

    Instead of a decimal digit string one may write "*" or "*m$" (for some decimal integer m) to specify that the field width is given in the next argument, or in the m-th argument, respectively, which must be of type int.

    So in your example it would be:

    printf("%*s\n", 5, "#");