You are going to have to use an ofstream as far as I know. Not that much work. To make it easier on yourself just make a function that takes a std::string as a parameter and prints it to the file. You can then just call the function instead of writing an output statement.
Wrapping the ostream object will prevent you from using some of its properties. The insertion operator (<<) should really be used directly to write the string to the stream.
But you could modify the function myprogram() to take an ostream.
1 2 3 4 5
void myprogram(ostream& os){
os << "Hi" << endl; // use endl to end lines, rather than just "\n"
}
Then you can call the function with cout or a file
#include <iostream>
#include <fstream>
void myprogram(ostream& os); // forward definition
int main()
{
// write to cout
myprogram(cout);
// and now to the file example.txt
ofstream ofs("example.txt");
if(ofs.is_open())
{
myprogram(ofs);
}
return 0;
}
// myprogram function goes here