Can pre-ANSI C Preprocessor handle symbolic constants in strings?

Roy Johnson rjohnson at shell.com
Mon Jun 10 11:42:52 AEST 1991


In article <1991Jun4.201629.29013 at athena.mit.edu> scs at adam.mit.edu (Steve Summit) writes:
> In article <RJOHNSON.91Jun4101340 at olorin.shell.com> rjohnson at shell.com (Roy Johnson) writes:
> >In article <DLBRES14.91May31050315 at pc.usl.edu> dlbres14 at pc.usl.edu (Brumley David M) writes:
> >> /* read a field of length FIELDSIZE */
> >> scanf("%" quote(FIELDSIZE) "s", buffer); 
> >> So that after the Preprocessor, the 'scanf' call becomes:
> >> scanf("%42s", buffer);

> >You might, for this example, want to do
> >scanf("%*s", FIELDSIZE, buffer);
> >which is standard/portable.

> I won't say "BZZT!", because I had halfway composed an article
> making the same suggestion, until I noticed that Mr. Brumley had
> asked about *scanf*, not printf.  There's this thoroughly
> annoying asymmetry between printf and scanf: for scanf, the '*'
> format-specifier flag indicates assignment suppression, *not*
> that the field width should be picked up from the argument list.
> Building a format string (either at compile time with string
> concatenation if you can hack it, or at run time with strcat
> and/or sprintf) is really what you have to do to get "variable"
> scanf field widths (unless you have an 8-10th edition scanf...).

You're right; I bone-headed it (cancelled my other posting
after seeing your correction, too).

In compensation, I illustrate your suggestion:

char fmt[10];

/* The first two %'s make one % in the string */
sprintf(fmt, "%%%ds", FIELDSIZE);
scanf(fmt, buffer);

which is, dare I say, standard, portable, and correct?
--
=============== !You!can't!get!here!from!there!rjohnson ===============
Feel free to correct me, but don't preface your correction with "BZZT!"
Roy Johnson, Shell Development Company



More information about the Comp.lang.c mailing list