I'm not sure if this is possible so hopefully someone can help figure this out. I'm using Dev C++ on WinXP.
This is a homework assignment and I can do it, I'm just trying to find a more efficient way.
I have code that prints out a bunch of stuff to the console. I also want to print the stuff to a file. Instead ofduplicating all my cout lines replacing cout with my fileobject I want to run through the code twice and the 2nd time through use a different namespace so that cout is now my fileobject and writes to a file instead of the console.
What I tried was creating the namespace before main like this
namespace mine
{
fstream cout;
}
Then inside main I put a for loop to run twice through all the couts that I want printed to the console and a file. At the very start of the for loop I have an if statement to execute some code on the 2nd run through the loop. This if statement looks like this.
if(p == 1)
{
using mine::cout;
cout.open("filename.txt", ios::out);
}
Now I figure that this should make cout my fileobject now. But I can't get it to work, it still prints to the console but the 2nd time through everything gets messed up.
I don't think that namespaces are the solution to your problem, I would use pointers intead:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
ostream *output;
fstream file;
//first point 'output' to 'cout'
coutput=&cout;
//do your first output like this:
*output<< "something";
//open file
file.open("file.txt");
// point 'output' to 'file'
output=&file;
//repeat your output (line 8)