Reputation: 1
So I'm designing a game where data is stored and read with text files. But I need to be able to do this in a repeating fashioned so the names of the text files need to be different for each one procedurally. I figured that using variables as the name would solve this issue but I am having a hard time doing this and getting the compiler to work with it. This is my current code to write 'hello' to a text file named 'test.txt':
ofstream myfile;
myfile.open("test.txt");
myfile << "hello";
myfile.close();
Now, I can replace "test.txt" with a single char* pointer or char array buffer, but I need to separate the name of the file with the .txt extension. The idea that I had was to somehow combine a char* variable for a name reference (Such as galaxy, star, planet, etc.), plus a numeric value (would have to be a big number, perhaps a double or float), plus the ".txt" text extension. This would then be one char pointer or array that would be compatible with myfile.open. Any ideas? I'm open to changing the process of this as long as I get the same end result.
Upvotes: 0
Views: 4019
Reputation: 73376
You should consider string
instead of char*
for your filename, as C++11 allows both types:
string myfilename="test";
myfile.open(myfilename+".txt");
myfile << "hello";
myfile.close();
To create more complex filenames you could then consider to use stringstreams: you can easily combine and format the filename using the usual output fromatting unctions/operators, and convert it to a string.
stringstream nn;
int counter=0;
nn<<myfilename<<counter<<".txt";
myfile.open(nn.str());
...
Upvotes: 1