9

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++;
}
1
  • 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. Commented Jul 11, 2012 at 17:03

3 Answers 3

16

In C++11:

while(k<50){
  ifstream myfile("file_no_" + std::to_string(k) + ".vtk");
  // myfile << "data to write\n";
  k++;
}
Sign up to request clarification or add additional context in comments.

5 Comments

+1: std::to_string? That's neat.
@Zeta, I was ecstatic when I saw someone here mention that and std::stoi, but depressed when I found out my implementation doesn't have either >.>
@chris: I recall it was me who mentioned std::stoi and you commented on my post. :-/
@Nawaz, It very well might have been. Thank you if it was, as at least I can recommend it to others :)
Not the first time I stole I good idea from @Nawaz.
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++;
}

1 Comment

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.
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);

13 Comments

+1 despite the potentially confusing variable names
MAGIC_BUFFER_SIZE? Hideously unsafe sprintf? You should be ashamed of yourself for posting this as a C++ answer.
@DeadMG: There is absolutely no chance of a problem occurring by using snprintf in this way.
@DeadMG: Simplest thing that can possible work FTW!!!!
@DeadMG: you are adding needless complexity to avoid a problem which is easily detected. In the process, you are contributing to a less maintainable body of code.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.