Reading a double from an istream in Hex

徘徊边缘 提交于 2019-12-12 19:14:52

问题


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.


回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!