'How to access an array from one member function in another member function?
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;
}
Solution 1:[1]
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);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Guillaume Racicot |
