我需要打印一个64位double作为十六进制字符串。
std::hexfloat。但是,在此之前,如何获得流的状态,以便将其重置为初始状态?-0x123.abc42p+10。我使用的语言是C++11。不是更多,不是更少。
发布于 2020-04-22 18:01:39
但是,在此之前,如何获得流的状态,以便将其重置为初始状态?
您可以使用流的flags()函数检索和保存当前设置,然后使用setf()函数还原它们,确保在“掩码”中包含std::ios_base::floatfield (第二个参数)。
如果目标是以尽可能高的精度打印,那么精度也必须被黑掉吗?或者这已经是六浮的一个特征了?
是。来自优先选择
十六进制浮点格式按照std::num_put::do_put规范的要求忽略流精度规范.
下面是一个简短的演示程序,可能会有所帮助:
#include <iostream>
using std::cout; using std::endl;
int main()
{
double test = -0x123.abc42p+10;
cout << std::fixed; // Change from the default for demo
cout << test << endl; // Display in "Current" format
auto fSave = cout.flags(); // Save current flags
cout << std::hexfloat; // Change to HEX float
cout << test << endl; // ... and display
cout.setf(fSave, std::ios_base::floatfield); // Restore float field
cout << test << endl; // Restored to previous settings!
return 0;
}发布于 2020-04-22 19:31:38
我需要它的项目实际上比C++11使用的要多一点,即GMP,它支持来自C99的打印修饰符%a:
// Include cstdarg / stdarg.h prior to gmp.h in the case
// we want va_list functions like gmp_vfprintf.
#include <cstdarg>
#include <gmp.h>
void func (double d)
{
gmp_printf ("%a", d);
}
#include <iostream>
void func (std::ostream& ost, double d)
{
auto len = gmp_snprintf (nullptr, 0, "%a", d);
char str[1 + len];
gmp_sprintf (str, "%a", d);
ost << str;
}https://stackoverflow.com/questions/61371454
复制相似问题