问题
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:
istringstream("0XD") >> fooistringstream("0XD") >> hex >> fooistringstream("D") >> hex >> foo
This is particularly concerning when I read here that the double istream extraction operator should:
The check is made whether the
charobtained from the previous steps is allowed in the input field that would be parsed bystd::scanfgiven 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.
回答1:
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
来源:https://stackoverflow.com/questions/37461993/reading-a-double-from-an-istream-in-hex