katmac <> writes:
> On Apr 28, 3: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?
>
> char junk;
> return !(sscanf( atoken, "%lf%c", dtmp, &junk ) == 1);
>
> The same pattern can be used for anything sscanf can decode (which is
> quite a lot)
Unfortunately, if the string being scanned represents a number
outside the range of the target type, the behavior of sscanf is
undefined. See C99 7.19.6.2p10 (it's split across pages in n1256).
--
Keith Thompson (The_Other_Keith)
kst- <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"