//Does the same as redirect_example.cpp but uses ofstream to write directly //to a file, rather than requiring the user to redirect the output. #include <iostream> #include <math.h> #include <fstream> #define NPOINTS 100 using namespace std; main() { //Now this line will appear on standard output at runtime, and the //file output_file.txt will have only the desired data. cout << "file has been opened!" << endl; //Not that this will overwrite the file, if it exists. ofstream fout("output_file.txt"); //The same formatting flags work as for cout. fout.precision(3); fout.setf(ios::scientific); float step_size = M_PI / NPOINTS; float values[NPOINTS] = {0}; float sin_of_values[NPOINTS] = {0}; for (int i = 0; i < NPOINTS; ++i) { values[i] = float(i) * step_size; sin_of_values[i] = sin(values[i]); fout << values[i] << " " << sin_of_values[i] << endl; } fout.close(); }