[英]Create loop to write multiple files in C++?
假设我有一个执行以下操作的程序:
for (i=1; i<10; i++)
{
computeB(i);
}
其中, computeB
仅输出值列表
computeB(int i)
{
char[6] out_fname="output";
//lines that compute `var` using say, Monte Carlo
string fname = out_fname + (string)".values";
ofstream fout(fname.c_str());
PrintValue(fout,"Total Values", var);
}
从另一个文件:
template <class T>
void PrintValue(ofstream & fout, string s, T v) {
fout << s;
for(int i=0; i<48-s.size(); i++) {
fout << '.';
}
fout << " " << v << endl;
}
在实施该循环之前, computeB
仅输出了一个值文件。 我现在希望它创建多个值。 因此,如果它最初创建了一个名为“ output.values”的文件,那么我该如何编写一个循环以创建“ output1.values”,“ output2.values”,...,“ output9.values”呢?
编辑:我忘了提到原始代码使用PrintValue
函数来输出值。 我最初试图节省空间并将其排除在外,但我只是造成了混乱
忽略代码中的所有语法错误...
i
计算输出文件名。 ofstream
。 ofstream
将var
写入。 该函数将如下所示:
void combuteB(int i)
{
char filename[100];
sprintf(filename, "output%d.values", i);
ofstream fout(filename);
fout << "total values";
fout << " " << var << endl; // Not sure where you get
// var from. But then, your
// posted code is not
// exactly clean.
}
您可以使用std::to_string()
从int
转换为string
:
void computeB(int i)
{
if (std::ofstream fout("output" + std::to_string(i) + ".values"))
fout << "total values" << " " << var << '\n';
else
throw std::runtime_error("unable to create output file");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.