Array Ofstream in C ++

I want 41 output files to be used in my project to write text to them. first create a string array list to name these output files, then I tried to define an array of objects from the stream 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; } 
+4
source share
2 answers

The following fixes are:

  • do not use new if you do not need to (you leaked all files and did not delete them properly, lead to data loss; streams may not be cleaned if you do not close them properly and the waiting output buffer will be lost)
  • Use proper array indexing (starting at 0!)
  • Call .open(...) from the default ofstream to open the file
  • Recommendations:
    • I would recommend against using namespace std; (not changed below)
    • I recommend reusing stringstream . This is a good practice.
    • They prefer to use C ++ loop cycle index indices ( for (int i = .... ). This prevents unforeseen surprises from i .
    • In fact, get the time and use the range to


 #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; } 
+6
source

You cannot invoke the constructor just like you. Try calling outFile[i].open(list[i].c_str()) . Pay attention to "open".

+1
source

Source: https://habr.com/ru/post/1439104/


All Articles