Array of Ofstream in c++

[亡魂溺海] 提交于 2019-12-05 16:14:09

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;
}

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!