_matherr doesn't get invoked when sscanf is called.

Discussion in 'C Programming' started by ishekara, Jun 23, 2004.

  1. ishekara

    ishekara Guest


    As per the msdn knowledge base.. i find the following

    "In an application developed with Microsoft C or C/C++, the sscanf()
    function is a good alternative to the atof() function to convert a string of
    digits into a floating-point number. If a string does not represent a valid
    number, atof() returns the value zero; sscanf() returns more useful error
    information. The application can use the error value from sscanf() with the
    matherr() function to perform error handling. The atof() function does not
    call matherr() unless an actual math exception occurs. "

    But even if the string is not correctly converted to float the _matherr()
    function is not being called. Is this a bug or something wrong?

    float f;

    char temp[]="1mmm1";

    int i=sscanf(temp,"%g",&f);

    Here f get assigned with 1 instead i was looking for an error.

    Any ideas how to solve this


    ishekara, Jun 23, 2004
    1. Advertisements

  2. Huh! Why not reading a good C-book in the first place?

    It's not really an error. But you could pre-check the domain with

    char checked[128];
    int ret = sscanf (checked, "%[0-9-+.eE]s", temp);

    if (ret == 1)
    int i = sscanf (checked, "%g", &f);

    but it wont prevent against malformed expressions like

    "12+3" or "45e"
    Yes. Better to use strtod() and to learn how to use the 2nd parameter. It's
    Emmanuel Delahaye, Jun 23, 2004
    1. Advertisements

  3. ishekara

    Eric Sosman Guest


    Well, no: it's only good for *some* `float' values.
    strtod() will happily and successfully convert a string
    to a `double' that can't in turn be converted to `float'.
    For example, on many implementations the string "1E300"
    is acceptable to strtod(), but yields a value larger
    than FLT_MAX.

    C99 introduced strtof(), which might be available on
    ishekara's implementation (it's worth looking, anyhow).
    If it isn't, I think the best he can do is to use strtod()
    with the usual error checks, and then either hope for the
    best or add further checks for range and perhaps precision:

    float flt;
    double dbl = strtod(...);
    /* usual checks here */
    if (fabs(dbl) > FLT_MAX
    || (fabs(dbl) < FLT_MIN && dbl != 0.0)) {
    /* `double' value outside `float' range */
    else {
    flt = dbl;

    .... but on systems that support infinities and/or NaNs,
    even this much isn't quite enough.
    Eric Sosman, Jun 23, 2004
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.