I'm trying to create a function that will take ostream
object as an argument, and then print to it. I plan to pass some of my fstream
(files), and cout
.
This is my code:
void printTask(int op1, int op2, int len, char operation, std::ostream& os = std::cout)
{
os << endl << " " << setw(len) << op1 << endl;
os << operation << " " << setw(len) << op2 << endl;
os << "-------------" << endl;
os << " ";
for(int i = 0; i < len; i++)
{
os << "?";
}
os << endl;
}
From main()
, it goes like this...
ofstream output("output.txt", ios::out);
cout << addition(xyz, output) << endl;
and that function looks like this:
int addition(int xyz, ofstream file)
{
int op1 = ...;
int op2 = ...;
char choice = ...;
printTask(op1, op2, xyz, choice, file);
printTask(op1, op2, xyz, choice, cout); //this cout is not necessary, default parameter
}
I get an error about std::ios::base
being private, but I did pass my ostream
object by reference so it doesn't try to use copy constructor.
Any ideas?
EDIT: Wanted to update this with an answer. Prototype for addition
was wrong, ofstream
should be passed by reference, instead of copying it.
This works:
int addition(int xyz, ofstream& file) {...}
Big thanks to @Jarod42