Search code examples
cstringc-strings

Can you use variables to specify field width?


I wanted to know if you can use a variable to specify field width, for example:

float g = 123.4567;
int x = 3;
int y = 4;
printf("%(%d).(%d)f", x,y,g);

I want my output to be: "123.4567", basically the same as

printf("%3.4f");

I don't think the compiler will read the current format, but maybe there is another way.


Solution

  • printf("%*.*f", x, y, g)
    

    The * in a format specifier means "I'll pass this number as an argument."