referencing variable names

I am running an algorithm and it must output several results into unique files.
I could do if-statements and open each file one at a time, however I rather keep it concise.


...
ofstream outputfile1;
ofstream outputfile2;
ofstream outputfile3;
ofstream outputfile4;

...

for (int i = 1; i < 5; i++)
{
outputfile(i).open("thisfile"&i&".txt");
}

...



On compilation I get this:
error *outputfile* was not declared in this scope.

The error refers to: outputfile(i).open("thisfile"i".txt");
where I have inserted: (i) into the filename. I have tried using '' and "" around i. I also have tried:

for (int i = 1; i < 5; i++)
{
char fileNum = '0' + i;
outputfile(fileNum).open("thisfile"&fileNum&".txt");
}
...and get the error: character constant too long for its type.


How do I make this work?

Thanks!



try this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
    const int OUTPUT_FILE_COUNT = 4;
    ofstream outputfile[OUTPUT_FILE_COUNT];

    .......

    for (int i(0); i < OUTPUT_FILE_COUNT; ++i)
    {
        std::string fileName("thisfile_");
        fileName += (static_cast<char>(i) + '0');
        fileName += "_.txt";
        outputfile[i].open(fileName.c_str());
    }

    .......
Last edited on
Works great! Thank you!
Last edited on
Topic archived. No new replies allowed.