-1

So, I'm trying to access a section of a data file through an array used by another member function but I'm not sure how. I created a member function that reads the data(from the file) in arrays, and I want to access a certain array(ba[i]) in 3 different member functions without altering the code.

void ATM :: ReadData(){

    ifstream atmdat("atmdata.txt",ios::in);

    int i=0;

    while (!atmdat.eof()){
        atmdat>>a[i]>>ba[i];
        i++;
    }

    nc=i;
}

I tried just using the array in the member function. But, I'm not sure how to include the variable i without constantly repeating the function unwarranted.

This is one of the member functions.

After this is compiled, I'm expecting the function to use the ba[i] array of data to do the calculations for one customer.

void ATM::Withdraw()
{
    cout<<"How much would you like to withdraw?"<<endl;
    double w;
    cin>>w;
    ba[i]-=w;
    cout<<"Balance:$"<<ba[i]<<endl;
}
Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141
  • 2
    Where are `a` and `ba` defined? Also, see [here](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) for information about eof. – ChrisMM Mar 29 '22 at 18:05
  • 2
    "*I want to access a certain array(ba[i]) in 3 different member functions*" - then make the array be a member of the class. Otherwise, you will have to pass it around using method parameters. Also, see [Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?](https://stackoverflow.com/questions/5605125/) – Remy Lebeau Mar 29 '22 at 18:07

1 Answers1

0

Usually, when a state need to be shared between member function, it's easy to store this array in the class.

struct ATM {
    void ReadData();
    void Withdraw(); 

private:
    // never store money as floating points, only use int or use fixed point
    std::vector<int> ba; // class member now
};

Another way would be to return the array, and send it as parameter:

struct ATM {
    std::vector<int> ReadData() const;
    void Withdraw(std::vector<int>& data); 

private:
    // ba is not a class member
};

std::vector<int> ATM::ReadData() const {
    std::vector<int> ba;
    ifstream atmdat("atmdata.txt",ios::in);

    int i=0;

    while (!atmdat.eof()){
        atmdat>>a[i]>>ba[i];
        i++;
    }

    nc=i;

    return ba;
}

void ATM::Withdraw(std::vector<int>& ba)
{
    cout<<"How much would you like to withdraw?"<<endl;
    double w;
    cin>>w;
    ba[i]-=w;
    cout<<"Balance:$"<<ba[i]<<endl;
}

int main() {
    ATM atm;

    // Get it from the function
    auto const atm_data = atm.ReadData();

    // Send it as parameter
    atm.ReadData(atm_data);
}
Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141