Jona Jona - 1 year ago 120
C++ Question

How to write/read to unknown input/output stream in c++

I need my program to do one of the following:

  1. Read from standard input and write to standard output

  2. Read from given file and write to another given file

The way of work is only determined in run-time.

This is what I tried

void runProgram(std::istream programIStream, std::ostream programOStream)
int x;
programIStream >> x; // Reading from program input stream

programOStream << "Writing to program output stream" << std::endl;

int main(int argc, char* argv[])
if(argc == 3)
std::ifstream ifs;[1], std::ios::in);
std::ofstream ofs;[2], std::ios::out);
runProgram(ifs, ofs);
runProgram(std::cin, std::cout);

return 0;

I assumed that inheritance will take care of everything, but this doesn't work.

What is the proper way to do what I need?

Answer Source

To actually do this, you have to something like this (pass by reference):

void runProgram(std::istream& programIStream, std::ostream& programOStream)

This should now solve your problem.

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