Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ofstream object as variable

I am trying to create multiple file according to filename in cpp. Using ofstream for that and could not achieve for now. Appreciate if anyone help me about that.

I am writing down here

static std::ofstream text1;
static std::ofstream text2;


class trial{
public:
if(situation == true) {
document_type = text1;
}
if(situation == false) {
document_type = text2;
}

document_type << "hello world" << "\n";

}

ofstream object as variable

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Assignment copies the objects, and it’s not possible to create copies of streams. You can only have reference to streams, and you can’t reassign references.

Instead I suggest you pass a reference to the wanted stream to the trial constructor instead, and store the reference in the object:

struct trial
{
    trial(std::ostream& output)
        : output_{ output }
    {
    }

    void function()
    {
        output_ << "Hello!\n";
    }

    std::ostream& output_;
};

int main()
{
    bool condition = ...;  // TODO: Actual condition

    trial trial_object(condition ? text1 : text2);
    trial_object.function();
}

Also note that I use plain std::ostream in the class, which allows you to use any output stream, not only files.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading