How to Create multiple files in C++

i want to generate multiple files using for loop .......
how can i keep a difrnt name of every file

#include<iostream.h>
#include<fstream.h>
#include<process.h>
#include<conio.h>
void main()
{
int i,n=5;
clrscr();
for(i=0;i<n;i++)
{
ofstream out_file( !!What shuld i write here!! ) ;
}
getch();
}
Use [code][/code] to highlight the code!!!
Some other things:
Don't use void main (), but rather int main ()
You should use the new headers (iostream, fstream etc) rather than the old ones...

Now to your question:
There are multiple ways to approach it:
As you are using an old compiler (which I assume to be Turbo C++),
you can't use std::string, making things more complex.

Now to the ways, you can create an array of arrays of chars (char FileName[a][b] where a and b are constant values...).
This will allow you to hole multiple strings, and you can add an ".txt" after their name in the out_file.

Or you can create a name which will change (by adding another character to the end).

If you have an access to std::string:
Create an array of std::strings, and follow the process I gave for an arrays of arrays of chars.
Or you can change the last character of the string*.

*Reference on std::strings:
http://www.cplusplus.com/reference/string/string/

Last edited on
I'm just trying out what Nisheeth suggests:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include<iostream.h>
#include<fstream.h>
#include<process.h>
#include<conio.h>
void main()
{
  int i,n=5;
  char FileName[5][10] =  {{"Name1"},{"Name2"},{"Name3"},{"Name4"},{"Name5"}};
  clrscr();
  for(i=0;i<n;i++)
  {
    ofstream out_file( FileName[i][] + ".txt" ) ;
  }
  getch();
}


I think that will work for you.
Last edited on
@Stewbond:
Change the ' on line 8 to " .
Last edited on
Topic archived. No new replies allowed.