Curious Behaviour of "sscanf"
Leo de Wit
leo at philmds.UUCP
Mon Jun 27 18:55:28 AEST 1988
In article <307 at sdrc.UUCP> scjones at sdrc.UUCP (Larry Jones) writes:
|In article <236 at c10sd3.StPaul.NCR.COM>, anderson at c10sd3.StPaul.NCR.COM (Joel Anderson) writes:
|| On a call to sscanf as follows:
|| if (sscanf(argv[3],"X=(%d,%d)",&y,&z) == 2)
|| and an input string where argv[3] is as follows:
|| "X=(1,4"
|| (not including the double quotes), why does sscanf in this case evaluate to
|| true? Sscanf matches the number of arguments but does not continue parsing
|| the control string (i.e. true even though the closing paren is missing)?
||
|| Perhaps this is correct - is it?
|
|Yep, that's the way scanf works. The problem is not that scanf doesn't
|continue parsing the control string -- it does -- the problem is that it
|doesn't have any way to let you know there was a problem. The definition
|of scanf states that it returns the number of items successfully converted;
|since it successfully converted 2 arguments, that's what it returned and
|that's what you were expecting.
Since nobody in the scanf discussion seems to hit the real point, I will
add my share.
Larry is correct as far as the behaviour of scanf() is conceirned;
only, most people seem to think that scanf is some kind of a parser.
It is not. The best scanf can do is possibly convert its next input
characters (whether from a string, file) to the current type in the
format string. For scanf there is not such thing as a correct syntax.
It's more like a (simple) lexical analyzer. So its behaviour is what
was to be expected.
As for the example, you could modify it to
char c, s[80];
if (sscanf(argv[3],"X=(%d,%d%c%s",&y,&z,&c,s) == 3 && c == ')')
A bit more cumbersome, but it allows better checking (the s[] is to check
for junk after the ')').
Leo.
More information about the Comp.lang.c
mailing list