To create file names, I would use std::ostringstream and operator<< .
If you want to use a container class, for example std::vector (for example, because at compile time you donβt know how big the ifstream array will be), since std::ifstream cannot be copied, t use vector<ifstream> , but you can use vector<shared_ptr<ifstream>> or vector<unique_ptr<ifstream>> ; eg:.
vector<shared_ptr<ifstream>> myFiles; for (int i = 0; i < count; i++) { ostringstream filename; filename << "info" << i << ".txt"; myFiles.push_back( make_shared<ifstream>( filename.str() ) ); }
With unique_ptr (and C ++ 11's move semantics):
vector<unique_ptr<ifstream>> myFiles; for (int i = 0; i < count; i++) { ostringstream filename; filename << "info" << i << ".txt"; unique_ptr<ifstream> file( new ifstream(filename.str()) ); myFiles.push_back( move(file) ); }
unqiue_ptr more efficient than shared_ptr , since unique_ptr is just a moving pointer, it does not count (therefore, the overhead is less than shared_ptr ). So in C ++ 11, you may prefer unique_ptr if ifstream not outside the vector container.
source share