Jona Jona - 2 months ago 12
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;
ifs.open(argv[1], std::ios::in);
std::ofstream ofs;
ofs.open(argv[2], std::ios::out);
runProgram(ifs, ofs);
}
else
{
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

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.