Variables as text file names

I am sorry if this was previously addressed. I searched for it and couldn't find it.

Is it possible to create a file with a variable as its name. For example let's say the database has the name of a person entered. Can a output file be put out with all the persons information but their name being the name of the output file?

Thanks in advance for the help.

sure. Just get a string from the user (or wherever) and use it as the filename when you generate the file.

1
2
3
4
5
6
7
8
string filename;

cout << "Input a filename:  ";
cin >> filename;

ofstream myfile( filename.c_str() );

myfile << stuff;
would a file extension go after the () or where. I have tried in a few spots and it keeps giving errors.

Thanks
Either the user inputs the file extension manually, our you can do filename + ".txt" or whatever before you try to open the file if it's always the same extension. Also, you ought not to use cin>> for strings; using getline() instead.
To add the file extension on the expression itself, you can use
std::ofstream myfile((filename+extension).c_str());
Or you can append the extension before opening the file.
filename.append(extension); //or filename+=extension;
Thanks for the help.
Topic archived. No new replies allowed.