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?

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() .

You can use sprintf()

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

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.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.