How can I specify a variable width in a scanf format string?

Q

How can I specify a variable width in a scanf format string?

✍: Guest

A

You can't; an asterisk in a scanf format string means to suppress assignment. You may be able to use ANSI stringizing and string concatenation to construct a constant format specifier based on a preprocessor macro containing the desired width:
#define WIDTH 3
#define Str(x) #x
#define Xstr(x) Str(x) /*
scanf("%" Xstr(WIDTH) "d", &n);

If the width is a run-time variable, though, you'll have to build the format specifier at run time, too:
char fmt[10];
sprintf(fmt, "%%%dd", width);
scanf(fmt, &n);

(scanf formats like these are unlikely when reading from standard input, but might find some usefulness with fscanf or sscanf.)

2015-10-26, 1158👍, 0💬