Search code examples
c++ofstream

C++ open multiple ofstreams in a loop


I need to open undefined number of files with ofstream to write in. the file names should have a format of plot1.xpm, plot2.xpm, plot3.xpm,... . The program looks like this: I don't know what should I place in stars.

for(m = 0; m < spf; m++){
    //some calculations on arr[]
    ofstream output(???);
    for(x = 0; x < n; x++){
        for(y = 0; y < n; y++){
            if (arr[x*n + y] == 0)
                output<<0;
            else output<<1;
        }
        output<<'\n';
        output.close();
    }

Solution

  • Use to_string:

    std::string filename = "plot" + std::to_string(m) + ".xpm";
    std::ofstream output(filename.c_str());
    

    If the pattern is more complex you can also use std::stringstream:

    std::stringstream filename_stream;
    // use "operator<<" on stream to plug in parts of the file name
    filename_stream << "plot" << m << ".xpm";
    std::string filename = filename_stream.str();
    std::ofstream output(filename.c_str());