question about passing arg in constructor??
Hi ,
I have a question about passing arguments in a constructor. I need to be able to pass a string in a constructor. THis string in turn will be used to open a file by that same name. I am storing this name as a private member of a class
I can pass the string, but when I get to opening a file by that name, I am not sure how to do this. I do have this in different files, but put in one file here.
I have posted the code below, along with where I am not sure how to open a file with the same name as the string that was passed in the constructor.
Any help will be appreciated. THanks for any help.
Code:
#include <iostream>
#include <fstream>
#include <string>
class data
{
public:
data(string); //contructor
void somefunction();
private:
string name; };
data::data(string somename)
{name = somename;}
void data::somefunction()
{
ofstream outfile;
outfile.open(name); //??? question about passing the stored string name here?
/*----- some output code----*/
outfile.close(); }
int main ()
{
data one("somename");
one.somefunction(); }
thanks - another question?
Hi ,
THanks a lot!!, that did work..
I do have 2 additional questions:
1) what does name.c_str() mean??? Could you please explain what exactly this means?? THanks a lot for the explanation.
2) I thought I had used code tags, but maybe I am not doing it correctly: I click on the "Insert Source Code" icon, it puts a [CODE] , and then I paste my code, and then I click the "Close all tags" icon which then places a [CODE]\
THen I post my message, am I supposed to do something additional??
THanks for the guidance!!!
Re: thanks - another question?
Quote:
Originally posted by smd
Hi ,
THanks a lot!!, that did work..
I do have 2 additional questions:
1) what does name.c_str() mean??? Could you please explain what exactly this means?? THanks a lot for the explanation.
2) I thought I had used code tags, but maybe I am not doing it correctly: I click on the "Insert Source Code" icon, it puts a [CODE] , and then I paste my code, and then I click the "Close all tags" icon which then places a [CODE]\
THen I post my message, am I supposed to do something additional??
THanks for the guidance!!!
1) the method returns a pointer to a const C-Style string.
2) No, you did it correctly.