lovespeed
lovespeed

Reputation: 5045

Define many output files in a loop in c++

I have c++ program in which I am running the same function many times but each time for a different value of a parameter. For each value of the parameter I want to output the result of the function to file whose name contains the value of the parameter. How to do this? Here is an example of what I want to do.

for(parameter = 10;parameter<=100;parameter*=10){
       ofstream file("file"<<parameter<<".txt", ios::out);
       function();
       file<<result;
       file.close();
}        

Upvotes: 0

Views: 981

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409136

You could do this with ostringstream:

for (int parameter = 10; parameter <= 100; paramter *=10 )
{
    std::ostringstream name;
    name << "file" << parameter << ".txt";

    // If your library is too old, you have to use
    // name.str().c_str()
    // to get the string
    std::ofstream file(name.str()); // or name.str().c_str() in C++03

    // ...
}

Upvotes: 4

Related Questions