Problems with scanf()
Mark Brader
msb at sq.sq.com
Wed Nov 7 09:08:11 AEST 1990
> ... it seems reasonable to do things like:
> if (sscanf(str, "%d %d", &x, &y) != 2) {
> fprintf(stderr, "Error parsing string.\n");
> exit(PARSE_ERROR);
> }
Sure. But don't imagine that you've checked the syntax of the string
by doing that. If it's supposed to contain precisely two numbers and
nothing else, one way to do it is:
char junk;
...
if (sscanf(str, "%d %d%c", &x, &y, &junk) != 2) {
fprintf(stderr, "Error parsing string.\n");
exit(PARSE_ERROR);
}
If there is anything after the second number, sscanf() will now
return 3. Notice incidentally that this is one of the few places where
it's reasonable in C to have a scalar variable of type char. Normally
time efficiency is more important than space efficiency for scalars,
so you use int, but here the address of the variable must be char *
to match the %c directive, and you aren't going to read from it anyway.
--
Mark Brader "Exercise 5-3: ... When should you
SoftQuad Inc., Toronto have stopped adding features...?"
utzoo!sq!msb, msb at sq.com -- Kernighan & Pike
This article is in the public domain.
More information about the Comp.lang.c
mailing list