4

Normally you have a set amount of placeholders in your printf(), which means I'd have to decide on a set amount of digit and string placeholders in advance.

Is it possible to make the amount of placeholders in your printf() dynamic or make specifically %d placeholders print an "empty" char

Pingu
  • 41
  • 4
  • what if i have multiple of these next to each other ? does it matter what that the "width" variable is named? or does the compiler just assume the variable in front of "value" is the the "width" variable ? – Pingu Sep 18 '19 at 10:33
  • 1
    @Pingu The _run-time_ (not the compiler) just takes "the next thing" from the parameter list when it finds `%*` and uses it as the width. So `printf( "%d %d", a, b )` will print two numbers using the default width, `printf( "%d %*d", a, widthB, b )` will print `a` normally, then use `widthB` (the next parameter) as the width for printing `b`. `printf( "%*d %*d", widthA, a, widthB, b )` will use a (separate) width for both `a` and `b`. – TripeHound Sep 18 '19 at 10:59

1 Answers1

4
printf("%*.*d", width, precision, value);

Using this format you can keep the width and precision flexible and feed them to the printf.

Consider the following example:

printf("<%*.*d>\n", 4, 1, 12);
printf("<%-*.*d>\n", 4, 3, 12);
printf("<%*.*d>\n", 0, 0, 0);
printf("<%*.*d>\n", 2, 0, 0);

Output:

<  12>                                                                                                                                                                   
<012 >                                                                                                                                                                   
<>
<  >
XBlueCode
  • 785
  • 3
  • 18
  • What i am looking for is a some kind of width value that simply makes the value "invisible" i was hoping that width = 0 would print "nothing" < > – Pingu Sep 18 '19 at 10:59
  • 1
    @Pingu So you want to _conditionally_ print values, not specifically control the width (which is what "_amount of digits_" make it sound like you were asking)? Off the top of my head, I don't remember there being a "conditional print" option (at least in the standard version of `printf` ... it _possible_ someone may have written a non-standard extension). – TripeHound Sep 18 '19 at 11:04
  • yeah, specifically i want to avoid printing the placeholder if the value = 0, but i still need the placeholder inside the printf() in case the value != 0 – Pingu Sep 18 '19 at 11:22
  • @Pingu, If this is the case then you need to put `precision = 0`, Please check the updated answer – XBlueCode Sep 18 '19 at 11:52