【问题标题】:Configuring std::ofstream format for floating point numbers为浮点数配置 std::ofstream 格式
【发布时间】:2016-06-14 14:54:26
【问题描述】:

有没有办法使用iomanip配置ostream来输出浮点数如下:

0.00000000000000E+0000
3.99147034531211E-0003
...

我正在将代码从 pascal 转换为 C++,我需要以完全相同的格式输出数字。最好使用 std::ofstream 而不是 fprintf 或其他 C 库函数。

【问题讨论】:

    标签: c++


    【解决方案1】:

    一种方法是使用一些字符串操作。使用科学记数法格式化为字符串流,然后在“e”上拆分字符串。现在你有了可以自己格式化的部分。

    #include <iostream>
    #include <iomanip>
    #include <sstream>
    #include <string>
    
    std::string format(double val)
    {
        std::ostringstream oss;
        oss << std::scientific << std::setprecision(14) << val;
        auto result = oss.str();
        auto match = result.find('e');
        if (match == std::string::npos)
        {
            // Should never get here -- maybe throw
        }
    
        oss.str("");
        auto exp = std::stoi(result.substr(match+1));
        oss << result.substr(0, match) << 'E'
                << std::setw(5) << std::setfill('0')
                << std::internal << std::showpos << exp;
        result = oss.str();
    
        return result;
    }
    
    int main()
    {
        std::cout << format(3.99147034531211e-3) << '\n';
        std::cout << format(6.02214085774e23) << '\n';
    }
    

    输出:

    3.99147034531211E-0003
    6.02214085774000E+0023
    

    【讨论】:

      【解决方案2】:

      您需要使用std::fixed

      示例程序:

      #include <iostream>
      #include <fstream>
      
      int main()
      {
        float f1 = -187.33667, f2 = 0.0;
        std::ofstream out("test.bin",std::ios_base::binary);
        if(out.good())
        {
          std::cout << "Writing floating point number: " << std::fixed << f1 << std::endl;
          out.write((char *)&f1,sizeof(float));
          out.close();
        }
        std::ifstream in("test.bin",std::ios_base::binary);
        if(in.good())
        {
          in.read((char *)&f2,sizeof(float));
          std::cout << "Reading floating point number: " << std::fixed << f2 << std::endl;
        }
        return 0;
      }
      

      用户 Texan40 的操作。欲了解更多信息:Here

      【讨论】:

      • 我绝对需要 std::scientific 而不是 std::fixed。我还需要 std::setprecision(14)。有了这些标志,我得到了 0.00000000000000e+00。但我需要 0.00000000000000E+0000
      • 您无法保证仅使用流操纵器并写入流。正如 Fred Larson 所描述的,一种选择是写入 ostringstream,提取结果字符串,对其进行处理以获得您需要的格式,然后将 that 输出到您的文件流。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-06
      • 2015-06-14
      • 2010-12-16
      • 2012-10-12
      • 2015-12-12
      • 1970-01-01
      相关资源
      最近更新 更多