Creating file names automatically C++
You can get a const char*
from an std::string
by using the c_str
member function.
std::string s = ...;
const char* c = s.c_str();
If you don't want to use std::string
(maybe you don't want to do memory allocations) then you can use snprintf
to create a formatted string:
#include <cstdio>
...
char buffer[16]; // make sure it's big enough
snprintf(buffer, sizeof(buffer), "file_%d.txt", n);
n
here is the number in the filename.
for(int i=0; i!=n; ++i) {
//create name
std::string name="file_" + std::to_string(i) + ".txt"; // C++11 for std::to_string
//create file
std::ofstream file(name);
//if not C++11 then std::ostream file(name.c_str());
//then do with file
}
... another way to bulid the filename
#include <sstream>
int n = 3;
std::ostringstream os;
os << "file_" << n << ".txt";
std::string s = os.str();