Can you specify variable field width in a scanf format string If possible how?

Answer:

Answer

You can't specify a variable field with a fixed format string, but you can get around this by making the format string variable:

 int width;
 char format[20];  /* or whatever size is appropriate */
 int value;

 ...
 sprintf(format, "%%%dd", width); /* generates a string like "%5d" */
 scanf(format, &value);

The only drawback to this method, other than requiring two statements, is that the compiler can't do a sanity check on the arguments to scanf like it can when the format is a string constant.

Answer

If you want to specify a variable width in a printf format string (as opposed to scanf), you can do the following:

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

That will use the value of "width" as the width for formatting the value of "num" as a decimal integer.

First answer by Mahousu. Last edit by Abbrev. Contributor trust: 7 [recommend contributor recommended]. Question popularity: 48 [recommend question].