logoalt Hacker News

CamperBob2 • today at 4:48 AM • 3 replies • view on HN

     if (sscanf(string,"%lf",&foo) != 1) 
        { 
        bad_float(); 
        }
This has the benefit of handling scientific notation, too, which some of the other CRTL functions inexplicably do not.

For extra reassurance, initialize foo to NaN or DBL_MAX or something, and verify that it is no longer equal to that value.


Replies

lelanthran • today at 5:36 AM

That doesn't detect overflows and underflows. Also changes based on locale, which is not thread safe (so you cannot set locale, convert, then unset locale).

rwmj • today at 10:03 AM

Annoyingly this doesn't detect certain errors. This is one thing I'd like to change in the next C standard, but (from discussions I had with someone who works in those standards) they don't want to break existing code. Which seems like a very bogus justification to me as that code is broken already.

Also the locale thing could be solved by adding another %-directive to say "this format string should be treated in the C locale", like %C (if it's not already used).

IOW this could be made to work, but human factors prevent it.

➕ show 1 reply
shakna • today at 5:28 AM

sscanf has locale things that make it include implementation-defined behaviour, doesn't it?

➕ show 1 reply