here is the question: The series of numbers: 1, 1, 2, 3, 5, 8, 13, 21, ….is known as Fibonacci series. Each number is the sum of the two preceding numbers. Write a C++ program that writes the first 5 Fibonacci numbers to a file fibnos.txt (in your local drive). The output is to be in text format, one number per line. (Note: Write a function to generate the Fibonacci numbers.)

my problem: is that the values are showing up in the file after excution i dnt know what i have done wrong please help.

my codes:

``````#include <iostream>
#include <fstream>
using namespace std;

int Fibonacci(int);
int main()
{
int n=5, i = 0, c, x;

for ( c = 1 ; c <= n ; c++ )
{
ofstream f;
f.open("mydata.txt");
cout<<("%d\n", Fibonacci(i))<<endl;
i++;
f<<Fibonacci(i)<<endl;
f.close();
}

return 0;
}

int Fibonacci(int n)
{
if ( n == 0 )
return 0;
else if ( n == 1 )
return 1;
else
return ( Fibonacci(n-1) + Fibonacci(n-2) );
}
``````

## Recommended Answers

As I interpret that code, only the last of the Fib numbers will be in the file.

You open it inside the loop, write a number, close the file.

The next pass through the loop will open the file, truncate the existing file (that is, delete previous content) and write …

## All 2 Replies

my problem: is that the values are showing up in the file after excution

What behavior were you expecting?

As I interpret that code, only the last of the Fib numbers will be in the file.

You open it inside the loop, write a number, close the file.

The next pass through the loop will open the file, truncate the existing file (that is, delete previous content) and write one new number.

The file open and close actions should be outside the for loop.