Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable sized padding in printf

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.

like image 920
Egil Avatar asked Nov 09 '10 11:11

Egil


People also ask

How do I add padding to printf?

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".

What is %d %f %s in C?

%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].

What is %B in printf?

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).

Can we use %d in printf?

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.


1 Answers

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.

like image 149
paxdiablo Avatar answered Sep 28 '22 08:09

paxdiablo