Is there a way to have a variable sized padding in printf
?
I have an integer which says how large the padding is:
void foo(int paddingSize) { printf("%...MyText", paddingSize); }
This should print out ### MyText
where the paddingSize should decide the number of '#' symbols.
If you want the word "Hello" to print in a column that's 40 characters wide, with spaces padding the left, use the following. char *ptr = "Hello"; printf("%40s\n", ptr); That will give you 35 spaces, then the word "Hello".
%s refers to a string %d refers to an integer %c refers to a character. Therefore: %s%d%s%c\n prints the string "The first character in sting ", %d prints i, %s prints " is ", and %c prints str[0].
The Printf module API details the type conversion flags, among them: %B: convert a boolean argument to the string true or false %b: convert a boolean argument (deprecated; do not use in new programs).
In C programming language, %d and %i are format specifiers as where %d specifies the type of variable as decimal and %i specifies the type as integer. In usage terms, there is no difference in printf() function output while printing a number using %d or %i but using scanf the difference occurs.
Yes, if you use *
in your format string, it gets a number from the arguments:
printf ("%0*d\n", 3, 5);
will print "005".
Keep in mind you can only pad with spaces or zeros. If you want to pad with something else, you can use something like:
#include <stdio.h> #include <string.h> int main (void) { char *s = "MyText"; unsigned int sz = 9; char *pad = "########################################"; printf ("%.*s%s\n", (sz < strlen(s)) ? 0 : sz - strlen(s), pad, s); }
This outputs ###MyText
when sz
is 9, or MyText
when sz
is 2 (no padding but no truncation). You may want to add a check for pad
being too short.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With