>Stu wrote:
[snippage]
char *buffer = "1234 - 5678";
int n, from, to;
n = sscanf (buffer, "%d%*s%d", &from, &to);
[or] When I change the vaule of buffer to char *buffer = "1234-5678"; ...
n = sscanf (buffer, "%d%*c%d", &from, &to); /*change from %s to %c */
Can somebody please provide me with one scanf() statement that can handle
both spaces and non spaces between my values. ...
In article <news:ck******* ***@news1brm.Ce ntral.Sun.COM>
Eric Sosman <er*********@su n.com> wrote: It sounds like you need "%*[- ]" (perhaps with additional
"don't care" characters listed). Note that since '-' is one
of the characters you want to skip, there'll be no way to get
a negative `to' value.
This will do the trick, but note that the %[ directive matches
*any* nonempty sequence of *any* of the characters in the scanset
(here just '-' and ' '), so this matches:
1234---5678
and:
1234 - -- - 5678
and:
1234- -5678
(which, as Eric Sosman noted, means there will be no negative "to"
values).
Another alternative is to use the scanf engine's white-space-matching
directives, e.g.:
n = sscanf(buffer, "%d\t%*c\b% d", &from, &to); /* odd way to write it */
Here the whitespace in the format -- \t and \b characters, which
is why it is odd since most people would just use a blank -- tells
scanf to read and ignore zero or more white-space characters in
the input (the string in the buffer, in this case).
The second whitespace directive is actually redundant, because %d
skips initial whitespace automatically anyway, so a more minimal
(and less odd) form is:
n = sscanf(buffer, "%d %*c%d", &from, &to);
If you would like to *require* that the single eaten-up character
be a hyphen, you can just put in a literal hyphen:
n = sscanf(buffer, "%d -%d", &from, &to);
The blank after the first "%d" reads and discards any arbitrary
amount of whitespace that follows the first "%d" conversion, the
"-" then matches only a literal '-' character, and the second %d
reads the second number (first reading and discarding any arbitrary
amount of whitespace, as usual). A final, more-symmetrical looking
variant is:
n = sscanf(buffer, "%d - %d", &from, &to);
which redundantly (but harmlessly) asks the scanf engine to skip
whitespace twice.
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it
http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.