Writing to a File
The preceding example, Take 4, works with writing to files, too. One of the many beauties of C++ is that the cout object is simply a file stream object, and you can use the same formatting techniques to write to a file.
First, add the following include line after your iostream include line:
#include <fstream>
Now try this code at the end of your main function:
ofstream f("/myfile.txt"); f << "Take 5" << endl; f.precision(3); f << showpoint; f.width(10); f << x << " "; f.width(10); f << y << " "; f.width(10); f << z << endl; f.width(10); f << p << " "; f.width(10); f << q << " "; f.width(10); f << r << endl; f << endl; f.close();
This is the exact same code as Take 4, except that it writes the output to a file instead of the console. Notice that I created a file stream called f. Then, instead of writing to cout, I wrote to f using the same f << x notation. That's pretty easy! And it's cool, too, because you can treat the cout and a file as the same thing. Take a look at this function:
void writestuff(ostream &o) { o << "a" << endl; }
All this function does is write a letter a and a newline to a file. If you create a new ofstream object as in Take 5, before closing the file you can call this writestuff file as follows:
writestuff(f);
This code passes the f object to the function, and the function writes to the file. Or you can pass the cout object like so:
writestuff(cout);
This tells writestuff to write the letter a to the console. That's reusability!