Writing to a file

W

Wilson

i am trying to create a program in which many different accounts are
to be created. I want each of the account's information to be stored
in a simple ".txt" file. is there anyway i can pass the contents of a
string (i.e two strings joined together e.g "account1" and ".txt") as
the name that is used when creating the file. i have previously used
ifstream/ofstream for creating a file, but with a given name set.

e.g

ofstream myfile;
myfile.open("account1.txt");
myfile << "hello";
myfile.close();
 
J

John Harrison

Wilson said:
i am trying to create a program in which many different accounts are
to be created. I want each of the account's information to be stored
in a simple ".txt" file. is there anyway i can pass the contents of a
string (i.e two strings joined together e.g "account1" and ".txt") as
the name that is used when creating the file. i have previously used
ifstream/ofstream for creating a file, but with a given name set.

e.g

ofstream myfile;
myfile.open("account1.txt");
myfile << "hello";
myfile.close();

Yes easily enough.

string part1 = "account1";
string part2 = ".txt";
ofstream myfile;
myfile.open((part1 + part2).c_str());

The only slightly tricky bit is the need for .c_str(). That is because
open needs a C type string instead of a C++ type string.

john
 
D

Daniel Kraft

Wilson said:
i am trying to create a program in which many different accounts are
to be created. I want each of the account's information to be stored
in a simple ".txt" file. is there anyway i can pass the contents of a
string (i.e two strings joined together e.g "account1" and ".txt") as
the name that is used when creating the file. i have previously used
ifstream/ofstream for creating a file, but with a given name set.

e.g

ofstream myfile;
myfile.open("account1.txt");
myfile << "hello";
myfile.close();

Try
myfile.open(yourString);

or
myfile.open("account1" + ".txt");

Cheers,
Daniel
 
M

Marcus Kwok

Juha Nieminen said:
How is that supposed to work? I don't think operator+ is defined
for two const char pointers.

You are correct. It needs to be something like:

myfile.open((std::string("account1") + ".txt").c_str());

but clearer would be to separate them into variables:

std::string base = "account1";
std::string extension = ".txt";

std::string filename = base + extension;
myfile.open(filename.c_str());
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,577
Members
45,052
Latest member
LucyCarper

Latest Threads

Top