c++ - 如何在 C++ 中将精确的浮点值保存和恢复到人类可读文件

标签 c++ floating-point

我需要能够从我的 C++ 程序中将精确的浮点值保存和恢复到人类可读(文本)文件中。我可以使用带有 sprinf 的 %A 格式来保存准确的值,但我找不到恢复它的方法。将 %A 格式与 sscanf 一起使用对我不起作用。

我的示例程序如下。它成功地将 0X1.921FB4D12D84AP+1 打印为 num1 的值,但是当我重新键入该值时,它将 num2 设置为 0。我在使用 GCC 4.7.3 的 Cygwin 环境(DLL 版本 1.7.22)中运行, G++ 编译选项包括:-std=gnu++11 -Wall -Wextra

#include <cstdio>
#include <string>
#include <iostream>

int main () {

    double num1 = 3.1415926;
    double num2;
    std::string input;
    int result;

    printf("%lA\n", num1);

    std::cout << std::endl;
    std::cout << "Input:" << std::endl;
    std::cin >> input;
    std::cout << "Got: " << input << std::endl;

    num2 = 0.0;
    result = sscanf(input.c_str(), "%lA", &num2);
    std::cout << "num2 is " << num2 << " and result is " << result << std::endl;

    return 0;
}

最佳答案

我建议您改为使用 atof() 函数,或使用 boost::lexical_cast。如果您有一个包含您的号码的字符串,两者都将完成您想要做的事情。

关于c++ - 如何在 C++ 中将精确的浮点值保存和恢复到人类可读文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18198459/

相关文章:

c++ - 2016 年之前的 Valgrind : Memory still reachable with trivial program using <iostream>

c++ - “如果”条件未正确评估

c - 为什么这种方法仍然会出现货币舍入误差?

c++ - 浮点类型作为 C++20 中的模板参数

compiler-errors - to_float()和除法错误

c++ - 为什么并行化会如此显着地降低性能?

c++ - 线程 C++ 的 lambda 内部函数调用

c++ - 如何正确使用 std::atomic_signal_fence()?

c - 为什么在 C 中转换为 int 不是所有 double

c - C语言中 float 相减