【发布时间】:2016-06-14 14:54:26
【问题描述】:
有没有办法使用iomanip配置ostream来输出浮点数如下:
0.00000000000000E+0000
3.99147034531211E-0003
...
我正在将代码从 pascal 转换为 C++,我需要以完全相同的格式输出数字。最好使用 std::ofstream 而不是 fprintf 或其他 C 库函数。
【问题讨论】:
标签: c++
有没有办法使用iomanip配置ostream来输出浮点数如下:
0.00000000000000E+0000
3.99147034531211E-0003
...
我正在将代码从 pascal 转换为 C++,我需要以完全相同的格式输出数字。最好使用 std::ofstream 而不是 fprintf 或其他 C 库函数。
【问题讨论】:
标签: 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 的操作。欲了解更多信息:Here
【讨论】:
ostringstream,提取结果字符串,对其进行处理以获得您需要的格式,然后将 that 输出到您的文件流。