Dynamic path names

Hey I am working on a game that allows saves in it, and long story short I was wondering if it was possible to have a dynamic path name. I know this sounds confusing so let me try to explain it.

right now instead of doing something like:
1
2
3
for( int i = 0; i < 5; i++ ) {
     file[i].open("saves/world"i"/player/health.txt");
}


I have to do:

1
2
3
file0.open("save/world0/player/health.txt");
file1.open("save/world1/player/health.txt");
//ect... 


Is there a way to do this efficiently with arrays and for loops? I use this combo a lot in my program because by changing one constant I can change how many skeletons are on the map (for example). This is the only part where I don't know how to do it, and it is slowing down development like crazy.
you almost have what you need:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
ofstream file[5];


void open_files();


int main()
{
   open_files();

   return 0;
}


void open_files()
{
   for (int i=0; i<5; i++)
   {
      stringstream s;
      s << "saves/world" << i << "/player/health.txt";

      file[i].open(s.str().c_str());
   }
}


if you need to call this in multiple source files then you may want to put the ope_files function in seperate header and cpp file and declare the array of ofstream objects as extern.
Another way is to make use of std::to_string to convert the integer to string and operator+ to combine the strings.
1
2
3
for( int i = 0; i < 5; i++ ) {
	file[i].open(("saves/world" + std::to_string(i) + "/player/health.txt").c_str());
}
Topic archived. No new replies allowed.