简体   繁体   English

创建循环以用C ++编写多个文件?

[英]Create loop to write multiple files in C++?

Let's say I have a program that does the follow: 假设我有一个执行以下操作的程序:

for (i=1; i<10; i++)
{
   computeB(i);
}

where the computeB just outputs a list of values 其中, 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);

}

From another file: 从另一个文件:

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;
}

Before implementing that loop, computeB just outputted one file of values. 在实施该循环之前, computeB仅输出了一个值文件。 I now want it to create multiple values. 我现在希望它创建多个值。 So if it originally created a file called "output.values", how can I write a loop so that it creates "output1.values", "output2.values", ..., "output9.values"? 因此,如果它最初创建了一个名为“ output.values”的文件,那么我该如何编写一个循环以创建“ output1.values”,“ output2.values”,...,“ output9.values”呢?

EDIT: I forgot to mention that the original code used the PrintValue function to output the values. 编辑:我忘了提到原始代码使用PrintValue函数来输出值。 I originally tried to save space and exclude this, but I just caused confusion 我最初试图节省空间并将其排除在外,但我只是造成了混乱

Disregarding all the syntax errors in your code ... 忽略代码中的所有语法错误...

  1. Use the input value i to compute the output file name. 使用输入值i计算输出文件名。
  2. Use the file name to construct an ofstream . 使用文件名构造一个ofstream
  3. Use the ofstream to write var to. 使用ofstreamvar写入。

Here's what the function will look like: 该函数将如下所示:

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.
}

You can use std::to_string() to convert from an int to a string : 您可以使用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.

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