简体   繁体   English

为浮点数配置std :: ofstream格式

[英]Configuring std::ofstream format for floating point numbers

Is there a way to configure ostream using iomanip to output floating point numbers as follows: 有没有一种方法可以使用iomanip配置ostream来输出浮点数,如下所示:

0.00000000000000E+0000 0.00000000000000E + 0000
3.99147034531211E-0003 3.99147034531211E-0003
... ...

I am translating code from pascal to C++ and I need to output numbers in exactly same format. 我正在将代码从pascal转换为C ++,我需要以完全相同的格式输出数字。 It is preferable to use std::ofstream instead of fprintf or other C library functions. 最好使用std :: ofstream代替fprintf或其他C库函数。

One way to do this is with some string manipulation. 一种方法是使用一些字符串操作。 Format to a stringstream using scientific notation, then split the string on the 'e'. 使用科学计数法格式化为字符串流,然后在'e'上分割字符串。 Now you have the parts you can format yourself. 现在,您拥有了可以自行格式化的部分。

#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';
}

Output: 输出:

3.99147034531211E-0003
6.02214085774000E+0023

You will need to use std::fixed 您将需要使用std::fixed

Sample program: 示例程序:

#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;
}

OP by user Texan40. 用户Texan40的OP。 For more info: Here 有关更多信息: 在这里

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

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