简体   繁体   中英

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, "#");

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, "#");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM