Newsgroups: comp.lang.c Path: utzoo!sq!msb From: msb@sq.sq.com (Mark Brader) Subject: Re: Problems with scanf() Message-ID: <1990Nov6.220811.25511@sq.sq.com> Organization: SoftQuad Inc., Toronto, Canada References: <1990Oct20.001637.28244@unislc.uucp> <324@brat.UUCP> <1204@mti.mti.com> Distribution: na Date: Tue, 6 Nov 90 22:08:11 GMT Lines: 31 > ... 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@sq.com -- Kernighan & Pike This article is in the public domain.