Basic C++ Question

jgbishop

Senior member
May 29, 2003
521
0
0
I haven't worked with streams in years, so I don't recall how to do this. I would like to be able to print data to either the screen or to a file. Is there a way I can write one print function that takes the data to be printed, and sends it to the proper location (based on a flag, let's say)? The answer is probably blindingly obvious, but it's Friday and I'm tired. :p
 

Spydermag68

Platinum Member
Apr 5, 2002
2,599
87
91
Overload the print function. One that take no arguments (screen) and one that takes a file name that is a string. Don't forget to do some error checkin when working with files.
 

jgbishop

Senior member
May 29, 2003
521
0
0
Well, I could certainly do that, but I'd like to know how I could do something like the following:

void myFunction(string myString, stream myStream)
{
// Something like the following:
myStream >> myString;
}

How would the guts of this function look to be able to write any string to any type of stream?
 

Spydermag68

Platinum Member
Apr 5, 2002
2,599
87
91
Format the the output in the print function and then make the return value the output stream. It would be upto the programmer outside the class to decide to where to send the output then. At a second look this dose make a better design since the class dose not need to know where the output is going just how to format it.
 

dighn

Lifer
Aug 12, 2001
22,820
4
81
I'm not sure I totally understand you but both screen (cout) and files (fstream) are derived from ostream, so you can have a function that takes an ostream reference then you can pass either cout or an fstream object to it. eg output(ostream& out, const string& in){out << in};
 

jgbishop

Senior member
May 29, 2003
521
0
0
Originally posted by: dighn
I'm not sure I totally understand you but both screen (cout) and files (fstream) are derived from ostream, so you can have a function that takes an ostream reference then you can pass either cout or an fstream object to it. eg output(ostream& out, const string& in){out << in};

Thanks for the pointer. This is just what I was looking for!