Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 228
  • Last Modified:

Dynamic Variable Names

I am trying to create a file stream and output destination which is distinct within each iteration of a for loop.  Would using dynamic variable names be a solution for this?  I have never used dynamic variables before so how would they be implemented? Or would there be another way around this?  Thanks.
0
aomega
Asked:
aomega
  • 2
1 Solution
 
jadams117Commented:
If I understand your question correctly you don't need to use dynamic variable names. You simply need to close the file and then open the new one for each iteration as follows..

#include <fstream>

int main
{

}
0
 
jadams117Commented:
Whoops - I think I pressed the button too early..

#include <fstream>

int main()
{
     const int numIterations = 2;

     std::string filename[numIterations];
     // fill filenames array with whatever you want
     filename[0] = "File0.txt";
     filename[1] = "File1.txt";

     std::ofstream outFile;

     for (int i = 0; i < numIterations; i++)
     {
          outFile.open(filename[i].c_str());
          // write stuff to your file
          outFile << "File" << i;
          outFile.close();
     }

     return 0;
}
0
 
aomegaAuthor Commented:
Good stuff =)
0

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now