我正在尝试编写一些代码来为模拟数据生成适当的文件名。在这里,我创建了一个字符串resultfile,它接受文本,整数和双精度并将它们连接成文件名。
这是我的(简化)当前代码:
string resultfile;
int Nx = 5;
double mu = 0.4;
//Simulation code here
resultfile += to_string(Nx) + "_mu" + to_string(mu) + ".csv";
ofstream myfile;
myfile.open ("./Datasets/"+ resultfile);
myfile << SimulationOutputs;
myfile.close();
这将.csv文件保存到我的/ Datasets /文件夹,但是,数据的文件名最终为:
&#34; 5_mu0.4000000.csv&#34;
当你的文件标题包含2个或更多个双打时,文件名会很快变得令人讨厌。我想获取文件名:
&#34; 5_mu0.4.csv&#34;
我在这里找到了一个似乎相关的问题:How to truncate a floating point number after a certain number of decimal places (no rounding)?,他们似乎在暗示:
to_string(((int)(100 * mu)) / 100.0)
但是,此编辑不会更改数据输出的文件名。我对C ++很新,所以这里可能有一个明显的解决方案,对我来说并不是很明显。
答案 0 :(得分:1)
您无法设置std::to_string
的精度,您可以自己编写,例如:
#include <sstream>
#include <iomanip>
template <typename T>
std::string to_string_with_precision(const T& a_value, const int n = 6)
{
std::ostringstream out;
out << std::setprecision(n) << a_value;
return out.str();
}
然后
resultfile += std::to_string(Nx) + "_mu" + to_string_with_precision(mu, 2) + ".csv";