Matt D Matt D - 1 year ago 128
C++ Question

Can I cast an ostream as an ofstream?

I have this code

ostream & operator<<(ostream & out, call_class & Org)
for (int i = 0; i<Org.count; i++)
out << Org.call_DB[i].firstname << " " << Org.call_DB[i].lastname
<< " " << Org.call_DB[i].relays << " " << Org.call_DB[i].cell_number
<< " " << Org.call_DB[i].call_length << endl;

//Put code to OPEN and CLOSE an ofstream and print to the file "stats7_output.txt".

return out; //must have this statement

As it says i need to use an
to print the contents of
to a file, can I just cast
as an
and use that?

For example, would this work?

new_stream = (ofstream) out;

This is the code in the main function that calls this function

cout << MyClass << endl;

MyClass is of type call_class
Assume that I cannot just change the parameter
to be of type

EDIT: Thank you for your help everybody. I know this was a difficult question to answer due to lack of clear instruction. My professor basically gave us two different versions of the same question and it was unclear what he was asking. I just wrote the data to a file outside of the function, hopefully that will be good enough.

Answer Source

You are misunderstanding how this operator works. Since the function takes an ostream & it will work with any class that derives from ostream like ofstream. This means that all we need to do is call this function on a ofstream instance and the output will be directed to the file that instance refers to. That would look like

std::ofstream fout("some text file.txt");
call_class Org;
// populate Org
fout << Org;

Now we will output to the file stream. The output function does not care where it is outputting to, you control that from the call site. This also gives you the advantage that the same operator works with all output streams. We could replace fout with cout, some stringstream, or any other stream derived from ostream.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download