c++hexscanfistringstreamiomanip

Reading a double from an istream in Hex


Given double foo I can assign it from a hex format string using sscanf like this:

sscanf("0XD", "%lg", &foo)

But I cannot seem to get an istringstream to behave the same way. All of these just write 0 to foo:

  1. istringstream("0XD") >> foo
  2. istringstream("0XD") >> hex >> foo
  3. istringstream("D") >> hex >> foo

This is particularly concerning when I read here that the double istream extraction operator should:

The check is made whether the char obtained from the previous steps is allowed in the input field that would be parsed by std::scanf given the conversion specifier

Why can't I read hex from an istream? I've written some test code here if it would be helpful in testing.


Solution

  • What you're looking for is the hexfloat modifier. The hex modifier is for integers.

    On compliant compilers this will solve your problem.

    #include <cstdio>
    #include <iomanip>
    #include <iostream>
    #include <sstream>
    using namespace std;
    
    int main() {
        double foo;
    
        sscanf("0xd", "%lg", &foo);
        cout << foo << endl;
    
        istringstream("0xd") >> hexfloat >> foo;
        cout << foo << endl;
    
        istringstream("d") >> hexfloat >> foo;
       cout << foo << endl; 
    }
    

    Using Visual Studio 2015 will produce:

    13
    13
    13

    Using libc++ will produce:

    13
    13
    0

    So I'm not sure of the legitimacy of istringstream("d") >> hexfloat >> foo