Hi,

I would need to create unique filenames appended by the iteration number.
For eg.

for( i=0;i<iterations;i++){
  ofstream outfile("iterfile"+"i"); // i.e filename should be iterfile0 for 1st iteration.
}

I need to cast "i" from int to char so I tried

ofstream outfile("iterfile"+(char)i)

but it did not work. How do I do this correctly?

Edited 6 Years Ago by Sandhya212: n/a

You can use a stringstream(http://www.cplusplus.com/reference/iostream/stringstream/). Remember to call mystringstream.str(""); at the beginning of your loop to clear it out (otherwise all the filenames will get stuck together as you go). Also, remember that ofstream takes a const char* for the filename so you need to use the .c_str() method of your resulting string (so your resultant string would be accessed as mystringstrim.str().c_str() .

Edited 6 Years Ago by jonsca: n/a

You can use sprintf()

<stdio.h>
sprintf(fileName,"iterfile%d",i);

Edited 6 Years Ago by nbaztec: n/a

stringstreams are a much cleaner solution than dirty C sprintf functions and should definitely be preferred when writing C++ code

stringstreams are a much cleaner solution than dirty C sprintf functions

Really? The only "dirty" thing I can think of (tedious would be my choice of words) is no std::string support in sprintf. So you need to figure out the maximum size of the file name buffer beforehand. Aside from that, sprintf doesn't seem any dirtier than stringstream for this particular use.

Edited 6 Years Ago by Narue: n/a

Yes, I find the use of C functions like sprintf dirty in C++ code. I guess I should've mentioned that this is somewhat a personal preference and not a strict rule though ;).

So I guess now the OP has all the information to chose between tedious(yes, it is a better description) or (in my eyes) cleaner solution ^^.

Dear all.

I used the sprintf version for the moment. I played around with stringstreams but was not successful. I shall do this once I get the major coding done :)
Thank you very much.

This question has already been answered. Start a new discussion instead.