I have written a simple code to practice some basics of c++ and some file handling. Haven't really used any of the OOP features. The program should open the input file and read each individual number from the input file. For each number “n” read from the input file, the program should write out the first “n” Fibonacci numbers to the output file. Please help me find bugs and improve my code.
Code:
#include "fibonacci.h"
using namespace std;
int main()
{
int number;
ifstream input;
ofstream output;
string inputfile;
string outputfile;
vector<int> validNumbers;
vector<int> invalidNumbers;
cout<<endl<<endl;
cout<<"Enter the input file name : ";
cin>>inputfile;
input.open(inputfile.c_str());
if(input.fail())
cout<<endl<<"Could not open input file"<<endl;
else
{
cout<<"Enter the output file name : ";
cin>>outputfile;
cout<<"Processing the input file..."<<endl;
while(!input.eof())
{
input>>number;
if( number<=0 )
cout<<endl<<"Skipping "<<number<<" as no fibonacci series is possible"<<endl;
else
ComputeFibonacci( outputfile.c_str(), number );
}
input.close();
}
}
Code:
#include "fibonacci.h"
using namespace std;
void ComputeFibonacci(const char* fileName, int number)
{
int first = 0;
int second = 1;
ofstream output;
output.open(fileName, ios_base::app);
if(output.fail())
cout<<endl<<"Can not open the output file"<<endl;
else
output<<endl<<endl<<"Number read : "<<number<<endl;
output<<"The fibonacci series is : "<<first<<"\t"<<second;
for(int i=2;i<number;i++)
{
int temp = second;
second = first + second;
first = temp;
output<<"\t"<<second;
}
output.close();
}