ofstream object as variable

71 Views Asked by At

I am trying to create multiple files according to a filename in cpp. Using ofstream for that, I could not achieve it for now.

I'd appreciate if anyone can help me with 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.

2

There are 2 best solutions below

0
Some programmer dude On BEST ANSWER

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.

0
Remy Lebeau On

You can't use statements at class scope, only declarations.

In any case, you need to use a reference variable for what you are attempting, eg:

std::ofstream& document_type = situation ? text1 : text2;
document_type << "hello world" << "\n";