Maggie K
Maggie K

Reputation: 31

end of file infinite while-loop

I have this program I'm writing to read and calculate principle and interest from a file and printing a table to an output file. Everything works fine except I can't figure out why I'm stuck in the while loop in the main. It prints all of my data correctly, but it constantly waits for another value and doesn't exit. Can anyone shed some light for me?

int main()
{
  ifstream inData;
  ofstream outData;
  float principle=0;
  int years;
  float rate;

  inData.open("inputdata.txt");
  if (!inData){
   cout<<"Error opening file."<<endl;
   return 1;}

  outData.open("outputdata.txt");
  if (!outData){
   cout<<"Error opening file."<<endl;
   return 1;}

  getData(inData, principle, years, rate);

  while(!inData.eof(){
    printTable(outData, principle, years, rate);

    principle=0;
    getData(inData, principle, years, rate);
  }

  return 0;
}

void getData (ifstream& inData, float& principle, int& years, float& rate)
{
 char temp;
 int temp2=0;

 inData.get(temp);

 while(temp!=' '){
    if(isdigit(temp)){
        temp2=temp-'0';
        principle=(10*principle)+temp2;}

    inData.get(temp);
 }

 inData>>years>>rate;
}

Upvotes: 0

Views: 540

Answers (1)

Zebra North
Zebra North

Reputation: 11482

After you have read the last record, it will call getData() for the final time. That will read temp, and will fail because it's at the end of the file. It then enters the while loop. temp will never equal a space, so it will never exit that loop. You will also be stuck if the file does not end in a space.

You need to check eof in the getData() while loop.

Upvotes: 4

Related Questions