Home > Justincase, Teachings > Files output in C++

## Files output in C++

All the programs that we normally use inputs from keyboard and give outputs on the screen. However, in a large scale computation, this situation is not effective. Thus, I have learnt how to produce outputs to a file, so that it can handle a large amount of data. I learned this back in 2007 and I have already forgotten about this code. Now, if I forget about this I know where to look.

Below I wrote a bit of source code that has to be compiled in C++. This program evaluates the exponential of a number from 0 to 3 using four different ways. The first three are using the Taylor polynomial of degree 1, 2 and 3 and the fourth way is using the built in exponential function from C++ itself. The output of this program is a file called “data.dat” that consists of five columns of numbers that can be used for plotting or other programs.

```#include <iostream> #include <fstream> #include <cmath> using namespace std; double taylor(double x, int n); int factorial(int n); int main() { double number; ofstream out_stream; out_stream.open("data.dat"); for (number = 0 ; number <= 3.01 ; number = number + 0.01) { out_stream << number << " "; out_stream << taylor(number,1) << "\t"; out_stream << taylor(number,2) << "\t"; out_stream << taylor(number,3) << "\t"; out_stream << exp(number) << "\n"; } out_stream.close(); return 0; } double taylor(double x, int n) { double y=1; for(int k=1; k<=n; k++) { y = y + pow(x,k)/factorial(k); } return y; } int factorial(int n) { if (n <= 1) return 1; else return n*factorial(n-1); } ```
I then used gnuplot to plot the output of the program. The plot is the following
where column 1 is the x-axis, while columns 2,3,4 and 5 are the evaluation of exponential of x-axis using four different ways. We can see that Taylor polynomials converge to exp(x).