Matt D Matt D - 17 days ago 5
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
ofstream
to print the contents of
out
to a file, can I just cast
out
as an
ofstream
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
out
to be of type
ofstream


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

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.

Comments