Trying to create 20 files using ofstream. I could name each individual file on creation, file01.txt, file02.txt ect but wondered if it was possible to use a string variable in place of say the file name (file01.txt) and then use a loop to create the other files. Does the name have to be a declared name or is the use of a variable possible?

ofstream outfile( "file01.txt", ios::app);

Can a variable be put in it's place (and if so how do you code it?) please. If not is there any other way around this?

Thanks Leppie

Use a stringstream to create the filenames.

#include <sstream>
stringstream ss;
ss<<filenamestring<<number<<".txt"; //number is the int from your loop index

Then use the .str() method of the stringstream to get the string in conjunction with the .c_str() operator of the string to get the char * that the ofstream method requires.

Member Avatar for iamthwee

Agreed.

An example:

#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
using namespace std;

string intToString(int t)
{
  std::string ch;

  ostringstream outs; 
  outs << t;   // Convert value into a string.
  ch = outs.str();   
     
  return ch;
}      


int main()
{
    for ( int i = 0; i < 100000; i++ )
    {
        
      std::string name = "file" + intToString(i) + ".txt";  
    
      ofstream write (name.c_str());
      write.close();
    }
   return 0;
  
}

Aside from an intToStr function, you should also create yourself a leadingZeros function, which you'll probably want to use here. You'll need both very often, so it's a good idea to create a small library with such functions for private use. You can also use boost's lexical_cast instead of intToStr.

Thanks so 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.