ADK
ADK

Reputation: 269

Write filename using sstream and fstream in C++

In my c++ program, I am saving output data in a file using sprintf and fstream just like below

#include <iostream>
#include <fstream>

char outname[50];
int n = 100;
sprintf(outname, "output_%s_%d.dat", "file", n);

ofstream fout;    
fout.open(outname);

How could I get a filename using std::sstring instead of sprintf and open that file with std::ofstream ? In above code filename is outname, which is being opened with std::ofstream.

Upvotes: 1

Views: 539

Answers (1)

AndersK
AndersK

Reputation: 36092

maybe something like this?

#include <sstream>

std::stringstream outname;

outname << "output_file_" << n << ".dat";
...
ofstream fout;
fout.open( outname.str().c_str() );

Upvotes: 4

Related Questions