c++ - How do I pass a ostream and use cout to display on the screen in a function? -


i want use istream , ostream parameter functions take , me work (read file, , display content on screen). know how istream:

std::ifstream myfile(...);  void foo(myfile);  void readfoo(std::istream &stream) {   int x, y;   stream >> x >> y;  //suppose file contains many rows of 2 numbers.   //store x , y somewhere  }  void writefoo(std::ostream &output) { ??? } 

and object should pass writefoo()?

update: here update got error message( cannot convert ostream ostream*)

writefoo(std::cout); writefoo(sd::ostream &out) {   out << somedata display screen; } 

you can pass any output stream derives std::ostream.

for example:

writefoo(std::cout);  //write stdout  std::ofstream file("output.txt"); //open/create file first writefoo(file);       //write output.txt 

hope helps.


Comments