Susliks Susliks - 1 year ago 74
C++ Question

Function, that takes string and number as parameter for creating filename

I have to create different data files in a loop.
There are three file-types i want to generate like


typeB%00d.txt and


For this i want to implement a function that takes a sequential number and a string as parameters.

Something similar to this:

void make_file(paarvec data, int count){

int size = data.size();
char filename[160];
sprintf(filename, "name%03d.txt", count);

ofstream out_data(filename);
for(int n=0; n<size; ++n){
out_data << data[n].first << "\t" << data[n].second << endl;

But is there a way that i also can change the "name" of the file with an argument. So that i can write:

std::string timestring = "timedata";
std::string timestring = "pathdata";

for(int i=0; i<N; ++i){
make_file(time_data, timestring ,count);
make_file(frac_data, fracstring ,count);
make_file(path_data, pathstring ,count);

Answer Source

Just change your function to:

void make_file(paarvec data, const std::string &name, int count){ 

  int size = data.size();
  char filename[160];
  snprintf(filename, sizeof(filename), "%s%03d.txt", name.c_str(), count);

Note I changed sprintf to snprintf - it is a good habit to prevent bad surprises in your code like buffer overflow.