I've written my progrma to use cout a lot, but now i want to output this to
a file instead of the screen. How do i do this Is it platform specific (if
so then sorry)
Thanks
Mike
If you're trying to do it from the command line without changing the
program, see Russell's answer.
If you want to modify the program to be generalized, here's an example of
implementing Jeff's technique [not that I consider his answer inadequate,
it's just that I've already written this up and this way it won't go to
waste ;-) ]. Note that all the actual output is performed by write_data(),
which is generalized in much the same way that non-member operator<<()'s
are written by convention (by taking an ostream & as a parameter):
//
// Generalizing I/O
//
#include <iostream>
#include <fstream>
#include <cctype>
#include <cstdlib>
using namespace std;
void write_data(ostream &os);
int main()
{
cout << "Output to screen (s) or file (f) ? ";
char dest;
cin >> dest;
if ((dest = std::tolower(dest)) == 's')
write_data(cout);
else if (dest == 'f')
{
ofstream of("gio_out.txt");
if (!of)
{
cout << "Couldn't create gio_out.txt. Bailing out.\n";
exit(1);
}
write_data(of);
}
else
{
cout << "Bad input. Re-run." << endl;
exit(1);
}
return 0;
}
void write_data(ostream &os)
{
os << "This is line 1\n";
os << "This is line 2\n";
os << "Etc.\n";
}
-leor