Fred
4/28/2011 8:47:00 PM
On Apr 28, 1:30 pm, Ben Bacarisse <ben.use...@bsb.me.uk> wrote:
> Fred <fred.l.kleinschm...@boeing.com> writes:
> > On Apr 28, 12:05 pm, David Mathog <dmat...@gmail.com> wrote:
> >> The C string to double conversion functions all seem to operate on the
> >> front of the input string, turning as much of it is as possible into a
> >> number. In a situation where the string should be entirely the
> >> number, and nothing should follow it, the best I have come up with to
> >> handle this case is:
>
> >> char *atoken;
> >> char *to;
> >> double dtmp;
> >> /* lots of other stuff, generating atoken */
> >> errno=0;
> >> dtmp=strtod(atoken,&to);
> >> if(errno || !to || *to != '\0'){
> >> fprintf(stderr,"fatal error: incorrect number syntax
> >> %s",atoken);
> >> }
>
> >> It works but isn't very pretty, what with 3 tests for the various
> >> failure modes. Is there another way to go about this, more along the
> >> lines of:
>
> >> if(cvtS2D(atoken,&dtmp)){
> >> }
>
> >> ?
> >> Where the hypothetical conversion function returns 0 if the input
> >> string is just a number, and something
> >> else for all the other cases?
>
> > strtod only sets errno if a range error occurred, so you do not need
> > that check to determine whether the field had bad characters in it.
>
> > You do not need the check (*to != '\0') since if 'to' is not NULL, it
> > points to the first unused character, which is guaranteed to be
> > something other than the NUL character.
>
> > That leaves you with:
> > if ( to ) { ... }
>
> I don't think that's right. If the programmer passes a valid pointer
> as the second argument, it will get set to something -- either the value
> of the first argument if no conversion could be done or to point just
> past the converted data (even if that is a null byte).
>
> As a result 'to == atoken || *to' is a sufficient test for failure in
> this case.
>
You're right. The first test (to==token) is needed in case 'token'
is empty, in which case *to is '\0', so just checking *to is
not sufficient to test for failure.
--
Fred K