Charles M. Reinke wrote:
"Eric Sosman" <er*********@sun.com> wrote in message
news:d8**********@news1brm.Central.Sun.COM...
[snip]
What will be your next step after discovering that the
string consists entirely of digits? If the next step is
"convert the string to its numeric equivalent," you could
just eliminate the test altogether, attempt the conversion
with strtol() or strtoul() (or even strtod(), if you want
to handle floating-point numbers), and then check whether
the conversion succeeded.
According to the man pages on my machine if strtod (for example) fails errno
MAY be set to something, but it doesn't seem to be required : "If no
conversion could be performed, 0 is returned and errno may be set to
EINVAL." So how can you verify that it succeeded? Is this specified in the
Standard (I don't have a copy handy), or it implementation specific and thus
non-portable?
You've got to look at two different kinds of failure: input
that doesn't have numeric form, and input that has correct form
but is out of range. To detect the first kind, use the second
argument to these functions, which (if non-NULL) designates a
`char*' variable that will receive a pointer to the first input
character that was not converted -- if no conversion could be
performed at all, this will be a pointer to the start of the
input string. If the input has the correct form but the result
is out of range, the function always sets errno to ERANGE. So
the whole dance goes something like this:
char *input = ...;
char *end;
double value;
errno = 0; /* in case it was ERANGE already */
value = strtod(input, &end);
if (end == input)
not_convertible();
else if (errno == ERANGE)
out_of_range();
else
successful_conversion();
If you want to require that the input consist only of a number
(not a number followed by other stuff), you could add a further
test for *end == '\0' -- that's up to you.
Sounds like a lot of tests, but in practice one usually lumps
all the error cases together, to get something like
errno = 0;
value = strtod(input, &end);
if (end == input || *end != '\0' || errno == ERANGE)
some_kind_of_error();
else
successful_conversion();
.... which isn't really all that daunting.
There are certainly more direct ways to answer exactly the
question the O.P. asked: "Does this string consist entirely of
digits?" The only reason I mentioned strtoxxx() is because the
next step after discovering that a string is composed of digits
is often to try to extract the value they represent; since
strtoxxx() will do the necessary checking anyhow, it may be
simpler just to attempt the conversion and see what happens.
--
Er*********@sun.com