Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of Ofstream in c++

I want 41 output files to use in my project to write text on them. first create a string array list to name those output files then I tried to define an array of ofstream objects and use list to name them, but I get this error that 'outfile' cannot be used as a function. Below is my code:

#include <sstream>
#include <string>
#include <iostream>
#include <fstream>
using namespace std ;
int main ()
{
  string list [41];
  int i=1;
  ofstream *outFile = new ofstream [41];

  for (i=1;i<=41 ;i++)
  {
    stringstream sstm;
    sstm << "subnode" << i;
    list[i] = sstm.str();
  }

  for (i=0;i<=41;i++)
    outFile[i] (list[i].c_str());

  i=1;
  for (i=1;i<=41;i++)
    cout << list[i] << endl;

  return 0; 
}
like image 969
vahidzolf Avatar asked Feb 18 '23 21:02

vahidzolf


2 Answers

See below for the following fixes:

  1. don't use new unless you have to (you were leaking all files and not properly destructing them will lead to lost data; ofstreams might not be flushed if you don't close them properly, and the pending output buffer will be lost)
  2. Use proper array indexing (starting from 0!)
  3. Call .open(...) on a default-constructed ofstream to open a file
  4. Recommendations:
    • I'd recommend against using namespace std; (not changed below)
    • I recommend reusing the stringstream. This is is good practice
    • Prefer to use C++-style loop index variables (for (int i = ....). This prevents surprises from i having excess scope.
    • In fact, get with the times and use ranged for


#include <sstream>
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
    ofstream outFile[41];

    stringstream sstm;
    for (int i=0;i<41 ;i++)
    {
        sstm.str("");
        sstm << "subnode" << i;
        outFile[i].open(sstm.str());
    }

    for (auto& o:outFile)
        cout << std::boolalpha << o.good() << endl;
}
like image 104
sehe Avatar answered Feb 21 '23 12:02

sehe


You can not call the constructor as you do. Try calling outFile[i].open(list[i].c_str()). Note the 'open'.

like image 34
Ivaylo Strandjev Avatar answered Feb 21 '23 12:02

Ivaylo Strandjev