4

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.

  • 2
    The answer is in the printf documentation, which is the first place you should have gone. – Jim Balter Mar 02 '14 at 19:32
  • 3
    @JimBalter To be fair to OP, it's one of the more obscure tokens that doesn't show up in many bits of example code. And on some man pages (e.g. http://www.freebsd.org/cgi/man.cgi?query=printf&sektion=3) the `*` token isn't even listed the same way as the other tokens, so it's pretty easy to miss. – Aaron Golden Mar 02 '14 at 19:50
  • It's so-called obcurity (I don't know of a single professional C programmer who doesn't know of it) has nothing to do with failure to read the documentation, and regardless of what is or isn't easy to miss, the man page is where the information is. You aren't being fair by excusing laziness. googling "printf variable precision" or "printf variable width" immediately comes up with the `*` syntax. In fact, one of those is an SO answer, so I'm going to vote to close this as a dup. – Jim Balter Mar 02 '14 at 20:11
  • possible duplicate of [Set variable text column width in printf](http://stackoverflow.com/questions/7105890/set-variable-text-column-width-in-printf) – Jim Balter Mar 02 '14 at 20:14
  • 3
    @JimBalter Take it easy dude, I'm a complete beginner and did not even know that there was documentation(I'm not a professional). I did google this question several times but could not think of the right search terms, including the ones provided. I'm only asking a question. –  Mar 02 '14 at 20:58
  • So much for "to be fair to the OP". Didn't even know there's documentation? Good grief. – Jim Balter Mar 02 '14 at 21:40
  • Ok man, best of luck. –  Mar 02 '14 at 22:13

1 Answers1

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

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

amalloy
  • 89,153
  • 8
  • 140
  • 205