Opening a file using constructor

Discussion in 'Computer Science & Culture' started by S.Tarafdar, Jul 13, 2003.

Thread Status:
Not open for further replies.
  1. S.Tarafdar Registered Senior Member

    Messages:
    35
    I want to open a file using constructor.It will ask the name of the file.My idea is such:

    Code:
    #include<iostream>
    # include<string>
    #include<fstream>
    using namespace std;
    
    
    int main(){
    cout<<"Enter the Name of the file:";
    string name;
    cin>>name;
    ofstream newfile(name.c_str());
    --------------
    --------------
    newfile.close();
    }
    
    why doesn't it work?Would you pls anybody give me an idea?
     
    Last edited: Jul 14, 2003
  2. Google AdSense Guest Advertisement



    to hide all adverts.
  3. okinrus Registered Senior Member

    Messages:
    2,669
    I think you want ofstream newfile(name.c_str());
     
  4. Google AdSense Guest Advertisement



    to hide all adverts.
  5. S.Tarafdar Registered Senior Member

    Messages:
    35
    But,It doesn't take space

    Pls see my modified codes.The file name does not take spaces now.
     
  6. Google AdSense Guest Advertisement



    to hide all adverts.
  7. okinrus Registered Senior Member

    Messages:
    2,669
    Yes if you want the filename to takes spaces you have to do something like this.

    <CODE>
    #include &ltiostream&gt
    #include &ltfstream&gt
    #include &ltstring&gt
    using namespace std;

    int main(void)
    {
    string name;

    cout << "Enter the Name of the file: ";
    getline(cin, name);

    ofstream newfile(name.c_str());
    newfile.close();


    return 0;
    }
    </CODE>
     
  8. S.Tarafdar Registered Senior Member

    Messages:
    35
    Thanks a lot.
     
Thread Status:
Not open for further replies.

Share This Page