ofstream filename

Hi,

I have a program where I need to periodically output some data to an external file. That is to say, each 10 iterations I want to save the info in sequentially numbered external files, something like this

out10.txt for ite 10
out20.txt for ite 20
out30.txt for ite 30

and so on. I wonder how can I implement this using ofstream in c++.


Thanks for your help,

Joel
You may also want to mess around with strings some too to get the file-names like you want.
http://www.cplusplus.com/reference/string/string/
Last edited on
stringstreams do what you want:
1
2
3
4
int n = 10;
stringstream ss;
ss << "out" << n << ".txt";
file.open ( ss.str().c_str() );
http://www.cplusplus.com/reference/iostream/stringstream/
Hi,

thanks for your help. I am trying the following, but I dont get the desired results. Any suggestion?


#include <iostream>
#include <fstream>
#include <sstream>

using namespace std;

int main () {

ofstream fout;

int n = 10;

stringstream ss;

for(int i=1;i<=n;i++)
{

ss << "out" << i << ".txt";

fout.open ( ss.str().c_str() );

fout<<i;

fout.close();
}

return 0;

}
move the stringstream declaration inside the for loop. Otherwise the new file name will be appended to the previous contents of the stream
Sweet, now is working fine. Thank you very much for your help.


Cheers,

joel
Topic archived. No new replies allowed.