Explore BrainMass

Infinite Loop C++

Can you find a bug in this program and then fix it so that it won't have an infinite loop?

#include <iostream>
#include <fstream>

using namespace std;

void CalculateAvgScore(ifstream &fIn,ofstream &fOut);

int main(int argc, char *argv[])
ifstream fin;
ofstream fout;

char inFileName[20],outFileName[20];

cout << "Enter the name of an existing text file: ";

cout << "Enter a name for output text file: ";
cin>>outFileName;,fstream::in);//open the input file,fstream::out);//open the ouuput file

CalculateAvgScore(fin,fout);//add one more field avgscore to the output file

fin.close();//close the input file
fout.close();//close the output file

system ("PAUSE");
return 0;

void CalculateAvgScore(ifstream &fIn,ofstream &fOut)
while (!fIn.eof())
char firstName[30],lastName[30];
int Scores[10]={0};
int totalScore=0;
double avgScore=0;

fIn>>lastName;//read lasttname
fIn>>firstName;//read firstname

if (lastName[0]=='') continue;//skip empty lines

for (int i=0;i<10;i++)
fIn >> Scores[i];//read score one by one
totalScore += Scores[i];

avgScore = (double)totalScore / 10;//calculate avg score

fOut << lastName;//write lastname
fOut << " ";//write one space

fOut << firstName;//write firstname
fOut << " ";

for (int j=0;j<10;j++)
fOut << Scores[j];//write score one by one
fOut << " ";

fOut << avgScore;//write avg score
fOut << "n";//write one change line character


Solution Preview

You should make sure that the file name is correct and input file is open before you call the while loop. I have added a line
if (!fin) {cerr<<"File not ...