Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inserting int variable in file name [duplicate]

Tags:

c++

Possible Duplicate:
Easiest way to convert int to string in C++

How can I insert int variable while creating .vtk file? I want to create file at every k step. i.e. so there should be series of files, starting from file_no_1.vtk, file_no_2.vtk, ... to file_no_49.vtk .

while(k<50){
  ifstream myfile;

  myfile.open("file_no_.vtk");

  myfile.close();

  k++;
}
like image 512
Mithil Parekh Avatar asked Jul 11 '12 17:07

Mithil Parekh


3 Answers

In C++11:

while(k<50){
  ifstream myfile("file_no_" + std::to_string(k) + ".vtk");
  // myfile << "data to write\n";
  k++;
}
like image 51
Robᵩ Avatar answered Nov 10 '22 01:11

Robᵩ


Use a stringstream (include <sstream>):

while(k < 50){
    std::ostringstream fileNameStream("file_no_");
    fileNameStream << k << ".vtk";

    std::string fileName = fileNameStream.str();

    myfile.open(fileName.c_str());

   // things

    myfile.close();

    k++;
}
like image 34
Zeta Avatar answered Nov 09 '22 23:11

Zeta


Like this:

char fn [100];
snprintf (fn, sizeof fn, "file_no_%02d.vtk", k);
myfile.open(fn);

Or, if you don't want the leading zero (which your example shows):

snprintf (fn, sizeof fn, "file_no_%d.vtk", k);
like image 2
wallyk Avatar answered Nov 10 '22 00:11

wallyk