1

I have a while loop as part of a class.

#include <iostream>
#include <iomanip>
#include <fstream>

struct familyFinance{             //add 3rd member familyFinance;
  int acctNos; float Balance; struct familyFinance *nextNodePointer;
  struct familyFinance *dynMemory; 
};

using namespace std;
class myFinanceClass {
private:
string fileName="";
familyFinance *ptrHead = nullptr;
public:
  void setFileName(string){ fileName="Lab5Data.txt";}
void readFileAndBuildLinkedList(){
ifstream Lab3DataFileHandle;
 
 
familyFinance *ptrHead=nullptr;
//familyFinance *dynFinancePtr=nullptr;
 familyFinance *tempPtr;
 tempPtr=ptrHead;

  Lab3DataFileHandle.open(fileName.c_str());
  while (!Lab3DataFileHandle.eof( )) {
    familyFinance *dynFinancePtr= new familyFinance;


 Lab3DataFileHandle >> dynFinancePtr -> acctNos; 
 Lab3DataFileHandle >> dynFinancePtr -> Balance;
 
 //   familyFinance *nextNodePointer = nullptr;
  if (ptrHead == nullptr)  {
    ptrHead  = dynFinancePtr;
}

else {      
 tempPtr =  ptrHead;  


 while  (tempPtr -> nextNodePointer != nullptr )
    tempPtr = tempPtr->nextNodePointer;
      tempPtr->nextNodePointer = dynFinancePtr; 

   }

  }
  Lab3DataFileHandle.close();


}
void spitThemOut(){
  familyFinance *tempNodePtr;
  tempNodePtr = ptrHead;

Here is the While Loop

  while (tempNodePtr) {


    cout << "Acct, Balance: " << setw(3)
         <<ptrHead->acctNos << " " <<ptrHead->Balance << endl;
 tempNodePtr = tempNodePtr->nextNodePointer;
  }
}

When I call the function from class in main I know it can read the function it just won't execute the while loop. What do I need to change to execute the while loop. It would be much apprenticed if you showed an example in your answer. Thank you for your time.

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
MR Hones
  • 61
  • 9

1 Answers1

0

If the while loop is in the method and defined in that class, that won't execute, cause it's not allowed by the language. Methods defined within the class are not allowed to have any loops. There are a few more restrictions that apply for methods defined within the class. Such a case can be solved by declaring the method in the class but defining it outside the class as shown below

class myFinanceClass {
    ...    // all the code before spitThemOut()
    void spitThemOut();
};

void myFinanceClass::spitThemOut() {
    ... // code to work
    while (tempNodePtr) {
        ...
    }
}
Debargha Roy
  • 2,320
  • 1
  • 15
  • 34