从Hex中的istream中读取一个double [英] Reading a double from an istream in Hex
问题描述
给定 double foo
我可以使用 sscanf
从十六进制格式字符串中指定它,如下所示:
Given double foo
I can assign it from a hex format string using sscanf
like this:
sscanf("0XD", "%lg", &foo)
但我似乎无法得到一个 istringstream
来表现相同的方式。所有这些只写0到 foo
:
But I cannot seem to get an istringstream
to behave the same way. All of these just write 0 to foo
:
-
istringstream(0XD)>> foo
-
istringstream(0XD)>> hex>> foo
-
istringstream(D)>> hex>> foo
istringstream("0XD") >> foo
istringstream("0XD") >> hex >> foo
istringstream("D") >> hex >> foo
当我阅读这里表示 double
istream
提取操作符应该:
This is particularly concerning when I read here that the double
istream
extraction operator should:
检查
char
从前面的步骤获得的输入字段允许在std :: scanf
给出转换说明符的情况下解析
The check is made whether the
char
obtained from the previous steps is allowed in the input field that would be parsed bystd::scanf
given the conversion specifier
为什么我不能从 istream
读取十六进制?如果它对测试有帮助,我已经写了一些测试代码这里。
Why can't I read hex from an istream
? I've written some test code here if it would be helpful in testing.
推荐答案
您要找的是 hexfloat 修饰符。 十六进制
修饰符用于整数。
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;
}
使用 Visual Studio 2015 将产生:
Using Visual Studio 2015 will produce:
13
13 >
13
13
13
13
使用 libc ++ 会产生:
Using libc++ will produce:
<13>
13
0
13
13
0
所以我不确定 istringstream(d)>>的合法性;> hexfloat>> foo
这篇关于从Hex中的istream中读取一个double的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!