簡體   English   中英

為浮點數配置std :: ofstream格式

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

有沒有一種方法可以使用iomanip配置ostream來輸出浮點數,如下所示:

0.00000000000000E + 0000
3.99147034531211E-0003
...

我正在將代碼從pascal轉換為C ++,我需要以完全相同的格式輸出數字。 最好使用std :: ofstream代替fprintf或其他C庫函數。

一種方法是使用一些字符串操作。 使用科學計數法格式化為字符串流,然后在'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

您將需要使用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的OP。 有關更多信息: 在這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM