1

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

Rorschach
  • 734
  • 2
  • 7
  • 22
  • Um... which line does the error occur on? – Brian Bi Apr 08 '16 at 23:42
  • I don't really know. Code::Blocks just opens `ios_base.h` and shows me that error. I later find more errors on lines where I call `addition` in `main()`. Like this: ` could not convert 'output' from 'std::ofstream {aka std::basic_ofstream}' to 'std::fstream {aka std::basic_fstream}'|` which doesn't really make much sense to me considering they are all `ostream` – Rorschach Apr 08 '16 at 23:46
  • 1
    Pass `ofstream` by reference, not by copy. – Jarod42 Apr 08 '16 at 23:51
  • You mean from main() to addition? – Rorschach Apr 08 '16 at 23:52
  • 2
    Yes, I mean fix `addition` prototype. – Jarod42 Apr 08 '16 at 23:53
  • Yes! That works, now it works as it should.` int addition(int difficulty, ofstream& file)`. Can you explain this please? This should be able to be copied?! Or am I mistaken? – Rorschach Apr 08 '16 at 23:55
  • 2
    iostreams do not copy well. More here: http://stackoverflow.com/questions/7903903/c-copy-a-stream-object By passing a reference, the compiler provides a reference to the stream and avoids the copying. What that reference looks like--pointer, silently performing the copy behind your back, or some other arcane voodoo--is totally up to the compiler. – user4581301 Apr 09 '16 at 00:03
  • Also, in `ofstream output("output.txt", ios::out);`, it is not necessary to pass `ios::out`, you only need the `ios::out` for instances of `fstream`, because this is precisely what `ofstream` does: it opens an `fstream` with a default mode of `ios::out`. – J. D. Jun 26 '18 at 19:50

0 Answers0