Is there such thing as invalid floating point ?

Discussion in 'C++' started by mathieu, Nov 27, 2007.

  1. mathieu

    mathieu Guest


    I am working on an IO library, and I am reading a binary blob which
    represent a floating point. I would like to know what is the correct
    way to interpret it. For integer type using a stringstream works like
    a charm, but for floating point I am getting a behavior that I don't
    quite understand, for instance (*).
    BTW NaN is the IEEE with all bit set, right ? What is the
    representation for infinity ?

    Thanks !

    #include <limits>
    #include <iostream>
    #include <sstream>

    int main()
    double inf = std::numeric_limits<double>::infinity();
    //double nan = std::numeric_limits<double>::quiet_NaN();
    std::cout << inf << std::endl;
    std::cout << nan << std::endl;
    std::stringstream ss;
    ss << inf;
    double out;
    ss >> out;
    std::cout << out << std::endl;
    return 0;

    mathieu, Nov 27, 2007
    1. Advertisements

  2. mathieu

    mathieu Guest

    D'oh ! I am missing the if test:

    if( ss >> out )
    std::cout << out << std::endl;

    My issue is solved, I know how to detect invalid floating point value.

    Sorry for the noise,

    mathieu, Nov 27, 2007
    1. Advertisements

  3. mathieu

    Ron Natalie Guest

    You need to check the error state here. The compiler will
    not read 'inf' into double. It fails and leaves the out variable
    with what ever non-initialized value it had before.

    double out = 123.456;

    if(ss >> out) {
    cout << "input failed (just for giggles out = " << out << "\n";
    } else {
    cout << out;
    Ron Natalie, Nov 27, 2007
  4. mathieu

    Ron Natalie Guest

    Don't forget to clear the error if you want to read anything further
    from that stream.
    Ron Natalie, Nov 27, 2007
  5. mathieu

    mathieu Guest

    Thanks !
    mathieu, Nov 27, 2007
    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.