Search code examples
csizeprintf

Set variable text column width in printf


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?


Solution

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