简体   繁体   中英

Configuring std::ofstream format for floating point numbers

Is there a way to configure ostream using iomanip to output floating point numbers as follows:

0.00000000000000E+0000
3.99147034531211E-0003
...

I am translating code from pascal to C++ and I need to output numbers in exactly same format. It is preferable to use std::ofstream instead of fprintf or other C library functions.

One way to do this is with some string manipulation. Format to a stringstream using scientific notation, then split the string on the '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

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. For more info: Here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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