
Constants in scanf() Format String?
|#define WIDTH 10
|
|and I want to use it in the format string for a scanf() call. Using:
|
|int i;
|scanf( "%WIDTHd", &i );
|
|doesn't seem to work, but:
|
|int i;
|
|scanf( "%10d", &i );
|
|works fine.
|What am I doing wrong?
Unlike the printf() function which can read its width and precision
specifiers from its argument list (by sticking in a `*' where the
width/precision is expected), scanf can't do this. (a `*' causes the
scanf() function to suppress assignment to the corresponding argument.)
But who cares? a `%d' format specifier causes the scanf() function
to skip any leading white space before it attempts to read a decimal
integral number. A simple `%d' format specifier makes scanf() read
strings like `123', ` 123'or ` 123', etc. correctly.
If you _really_ insist doing this, you have to compose the format
string yourself. Something like this'll do:
char buf[ENOUGH_CHARS];
int i;
sprintf(buf, "%%%dd", WIDTH);
scanf(buf, &i);
(please note the double `%%'; it cause the sprintf() function to
output a single `%' character.)
kind regards,
----------------------------------------------------------------------------
Doc, I wanted to talk to you about my problem with premature ... *whoops*