Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Object-Oriented Programming C++ - I have to output my program to a file called \

ID: 3732647 • Letter: O

Question

Object-Oriented Programming C++ - I have to output my program to a file called "sim.txt". My simulation is a function obviously so I'm not able to do a thing like:

std::ofstream outputFile;

outputFile.open("sim.txt", std::ios::out);

outputFile << runSimulation(franchises, days);

outputFile.close();

Because I then get the error that is that the operator << does not recognize an ofstream to a void function. runSimulation also has another print function nested within it called printRundown that runSimulation calls once per day.

Signatures for printRundown and runSimulation:

void runSimulation(std::vector<HotdogStand> &franchises, int days);

void printRundown(const std::vector<MyAwesomeBusiness::HotdogStand> &franchises);

I'd prefer you to overload the operator << to make it happen, but if there is a way that you know of that is easier then please do go with that. I'm having a hard time figuring this problem out. Thanks

Explanation / Answer

helper class will help and overload operators that takes care of streaming to two streams. Use the helper class instead of trying to override the standard library implementations of the overloaded operator<< functions. See below example.

#include <iostream>

#include <fstream>

struct MyStreamingHelper

{

    MyStreamingHelper(std::ostream& out1,

                      std::ostream& out2) : out1_(out1), out2_(out2) {}

    std::ostream& out1_;

    std::ostream& out2_;

};

template <typename T>

MyStreamingHelper& operator<<(MyStreamingHelper& h, T const& t)

{

   h.out1_ << t;

   h.out2_ << t;

   return h;

}

MyStreamingHelper& operator<<(MyStreamingHelper& h, std::ostream&(*f)(std::ostream&))

{

   h.out1_ << f;

   h.out2_ << f;

   return h;

}

int main()

{

   std::ofstream fl;

   fl.open("test.txt");

   MyStreamingHelper h(fl, std::cout);

   h << "!!!Hello World!!!" << std::endl;

   return 0;

}