How to check data input

M

Mok-Kong Shen

If I with scanf input a couple of hex values to unsigned long int with
%x and there is error in data, e.g. 3g, how could I check that so that
I could repeat the scanf statement?

Thanks in advance,

M. K. Shen
 
D

Dr Malcolm McLean

If I with scanf input a couple of hex values to unsigned long int with
%x and there is error in data, e.g. 3g, how could I check that so that
I could repeat the scanf statement?
if( scanf("%lx %lx", &a, &b) == 2)
/* scanf successfully converted two long int values */
else
/* scanf was unsuccessful. You need some sort of flow control to go
back
to your scanf() call and try again */

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.
 
K

Keith Thompson

Dr Malcolm McLean said:
if( scanf("%lx %lx", &a, &b) == 2)
/* scanf successfully converted two long int values */
else
/* scanf was unsuccessful. You need some sort of flow control to go
back
to your scanf() call and try again */

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.
 
P

Peter Nilsson

Keith Thompson said:
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.

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.
 
K

Keith Thompson

Peter Nilsson said:
The behaviour of %8lx is certainly well defined.

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,104
Messages
2,570,643
Members
47,246
Latest member
rangas

Latest Threads

Top