从 Hex 中的 istream 中读取双精度数

Reading a double from an istream in Hex

给定 double foo 我可以使用 sscanf 从十六进制格式字符串分配它,如下所示:

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

但我似乎无法让 istringstream 以同样的方式行事。所有这些只是将 0 写入 foo:

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

当我读到 here double istream 提取运算符应该:

时,这尤其令人担忧

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

为什么我不能从 istream 中读取十六进制?我已经写了一些测试代码here如果对测试有帮助的话。

您要查找的是 hexfloat 修饰符。 hex 修饰符用于整数。

在兼容的编译器上,这将解决您的问题。

#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; 
}

使用 Visual Studio 2015 将产生:

13
13
13

使用 libc++ 将产生:

13
13
0

所以我不确定 istringstream("d") >> hexfloat >> foo

的合法性

这个,包括环回似乎适用于两个最近的编译器和至少 c++17,例如:

MSVC 16.7.0 预览版 2 C++ 标准/最新

Clang 10.0.0 -std=c++2a

但对于 GCC 失败,例如:

GCC 10.0.1 -std=c++2a 使用 libstd++

此错误已暂停,等待 C++ 标准 WG21 的决定

https://gcc.gnu.org/bugzilla//show_bug.cgi?id=81122

错误 81122 - [DR 2381] 在读取 std::hexfloat >> f;

时解析 f 在“0”后停止

https://cplusplus.github.io/LWG/issue2381 最后修改时间:2018-08-24

并且似乎由于不明原因而停滞不前:-(