C++循环中打开多个流

C++ open multiple ofstreams in a loop

本文关键字:循环 C++      更新时间:2023-10-16

我需要打开未定义数量的带有ofstream的文件来写入。 文件名的格式应为plot1.xpm,plot2.xpm,plot3.xpm,... .该程序如下所示:我不知道我应该在星星上放什么。

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();
    }

使用 to_string

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

如果模式更复杂,您还可以使用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());