66

In order to determine the size of the column in C language we use %<number>d. For instance, I can type %3d and it will give me a column of width=3. My problem is that my number after the % is a variable that I receive, so I need something like %xd (where x is the integer variable I received sometime before in my program). But it's not working.

Is there any other way to do this?

3
  • 3
    In general, instead of "not working" you should copy-paste the exact error message you received. Aug 19, 2011 at 4:29
  • @luserdroog There is no error message when printf fails. It just silently gives incorrecy output.
    – S.S. Anne
    Sep 1, 2019 at 23:18
  • Is this related to the eight years old question? And what output do you get and what are you expecting? What does the call look like? Sep 2, 2019 at 8:31

2 Answers 2

116

You can do this as follows:

printf("%*d", width, value);

From Lee's comment:
You can also use a * for the precision:

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

Note that both width and precision must have type int as expected by printf for the * arguments, type size_t is inappropriate as it may have a different size and representation on the target platform.

1
  • @SouravKannanthaB: no this does not work for scanf: the * means suppress assignment and no pointer argument is provided for this conversion specification. There is no way to specify the number as an argument, but you can compose a format string with snprintf as a work-around. scanf_s from optional and controversial Annex K attempted to address related issues, but the specification is inadequate for simple use.
    – chqrlie
    Mar 15, 2021 at 9:39
8

Just for completeness, wanted to mention that with POSIX-compliant versions of printf() you can also put the actual field width (or precision) value somewhere else in the parameter list and refer to it using the 1-based parameter number followed by a dollar sign:

A field width or precision, or both, may be indicated by an asterisk ‘∗’ or an asterisk followed by one or more decimal digits and a ‘$’ instead of a digit string. In this case, an int argument supplies the field width or precision. A negative field width is treated as a left adjustment flag followed by a positive field width; a negative precision is treated as though it were missing. If a single format directive mixes positional (nn$) and non-positional arguments, the results are undefined.

E.g., printf ( "%1$*d", width, value );

2
  • 1
    Your example doesn't fit the language. It should be "%*1$d"
    – Jim Balter
    Mar 2, 2014 at 20:18
  • Furthermore, you should specify both argument by means of n$, like so: printf("%2$*1$d", width, value);. Aug 7, 2014 at 11:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.