Thanks in advance,
M. K. Shen
Seriously - don't use scanf for this.
Capture the input in a string. Parse the string yourself. The strtol and
strtoul functions offer excellent error detection mechanisms for such
parsing, since they report on the address of the first character in the
input string that was not suitable for conversion.
Something like this:
while(printprompt(), fgets(buf, sizeof buf, stdin) != NULL)
{
char *left = buf;
char *right = buf;
int success = 0;
int inm = strtoul(left, &right, 16);
if(right > left) /* at least one character was converted */
{
left = right;
int inn = strtoul(left, &right, 16);
if(right > left) /* ditto */
{
++success;
use(inm, inn);
}
}
if(!success)
{
printerror();
}
}
Note that the above is a fragment, not a complete program. The details
of printprompt(), printerror(), and use() are left as an exercise.
--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
"Usenet is a strange place" - dmr 29 July 1999
Sig line vacant - apply within
However Richard's advice to avoid scanf() is good. It's hard to write
a bulletproof interface with scanf() that will react correctly to all
user errors.
In fact, I believe it's impossible, at least if you use the numeric
input formats such as "%lx". If the value being read is outside the
range of the target type, the behavior is undefined.
--
Keith Thompson (The_Other_Keith) ks...@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
The behaviour of %8lx is certainly well defined.
The only real problem with scanf is that most input conversion
specifiers will ignore leading whitespace, including new-lines.
--
Peter
Good point, I hadn't thought of that. But if unsigned long is more
than 32 bits wide, there are values you can't read with %8lx, and if
its width isn't a multiple of 4 bits (admittedly unlikely) there's
no safe format. And of course that trick doesn't work for decimal.
> The only real problem with scanf is that most input conversion
> specifiers will ignore leading whitespace, including new-lines.
You can avoid the new-line problem by reading a line into memory and
then using sscanf() (but you still have the overflow problem).
Surely it wouldn't have been that difficult ot specify the behavior of
*scanf() on numeric overflow.