nordhagen nordhagen - 3 months ago 21
C++ Question

Format strings c++

I'm new to c++, and can't find how to set different file names every time a loop is running. I want to make a new file every time the loop is running, and of course I have to give them different file names. Otherwise the same file is just updating. In Python it can easily be done by

for i in range(10):
filename = "myfile%f.dat" % i


but I can't find a similar syntax in c++. I hope someone can help me, I made a example script below (with Python syntax for the format string) which hopefully makes it more clear what I'm trying to do.

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main ()
{
for(int i = 1; i < 11; i += 1)
{
string filename; filename = "table%d.dat"%i;
ofstream infile;
infile.open( filename.c_str());
infile << "multiplication table for " << i << endl;
for(int j = 1; j < 11; j+=1)
{
infile << j*i << endl;
}
infile.close();
}
return 0;
}

Answer

Here are a couple of alternatives:

  1. Use std::to_string and string concatenation:

    std::string filename = "table" + std::to_string(i) + ".dat";
    
  2. Use std::ostringstream:

    std::ostringstream iss;
    iss << "table" << i << ".dat";
    std::string filename = iss.str();