8

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++;
}
Community
  • 1
  • 1
Mithil Parekh
  • 93
  • 1
  • 1
  • 5
  • 1
    Dupe of all of the `How to convert int to string?` questions here. Just so you know, there's a `std::to_string` function in C++11. – chris Jul 11 '12 at 17:03

3 Answers3

16

In C++11:

while(k<50){
  ifstream myfile("file_no_" + std::to_string(k) + ".vtk");
  // myfile << "data to write\n";
  k++;
}
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
4

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++;
}
Zeta
  • 103,620
  • 13
  • 194
  • 236
  • I want to point out that there was a question recently that used `myfile.open (fileName.str().c_str());`, causing the confusion. Make sure not to do that, and instead make the string variable. – chris Jul 11 '12 at 17:14
3

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);
wallyk
  • 56,922
  • 16
  • 83
  • 148