繁体   English   中英

从十六进制 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

当我在这里读到double istream提取运算符应该:

检查是否允许在输入字段中使用从前面步骤获得的char ,在给定转换说明符的情况下,该输入字段将由std::scanf解析

为什么我不能从istream读取十六进制? 如果对测试有帮助,我在这里写了一些测试代码。

您正在寻找的是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++ std /latest

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM