Set variable text column width in printf

Alaa M. picture Alaa M. · Aug 18, 2011 · Viewed 45k times · Source

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?

Answer

Oliver Charlesworth picture Oliver Charlesworth · Aug 18, 2011

You can do this as follows:

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

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

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