Question

Im doing a project that stimulate the ATM in C++ and having some troubles with the accumulators, my question is: I am use switch (here is case 1) to change the values of 2 variables which are declared inside the function that contains the switch(), however the values only change inside case 1 and they reset themselves to the original value (like const declaration), so when I try to print the checking and saving (in case 3 and 4) it prints out the original amount (1000). So I dont know what I did wrong here. Problem is not with the amount, I have tried replacing amount with a numeric value but still doesnt work. Please help

int transactions()
{   
    double checking = 1000.00, saving = 1000.00;
    double amount;
    switch (inputRange(menu()))
    {
    case 1: system("cls");
            amount = getAmount("Enter an amount to transfer from checking to saving: ");
            checking -= amount; 
            saving += amount;
            cout << checking << " " << saving; // they only change inside case 1
            cout << "\nTransaction completed! \n\nPress ENTER to return to main menu...";
            cin.ignore(99,'\n');
            break;

updates*** I already got it guys, thanks, just forgot about the &, this works

   int transactions(double &checkBal, double &saveBal)
{       
    double amount;

    //set precision
    cout << fixed << showpoint << setprecision(2);

    switch (inputRange(menu()))
    {
    case 1: system("cls");
            checkingToSaving (getAmount("Enter an amount to transfer from checking to saving: "), checkBal, saveBal);
            cout << "\nTransaction completed! \n\nPress ENTER to return to main menu...";
            cin.ignore(99,'\n');
            break;
Was it helpful?

Solution

The issue is that checking and saving only exist for the duration of a single call to transactions().

They spring into existence when transactions() is called, get initialized, your code changes them, and they disappear the moment transactions() returns. When the function is called again, the whole cycle repeats.

The two variables need to exist outside the function (probably as data members of some class).

OTHER TIPS

Declare a 'customer' class, (with name, address, savings, checking etc. members). Create instances outside 'transactions' and pass in an instance as a parameter.

That, or DB.

A crude answer to your immediate problem is to use static variables:

int transactions()
{   
    static double checking = 1000.00;
    static double saving = 1000.00;
    .
    .

This type of approach only gives you one instance of checking and saving. If you want to extend your program to have multiple accounts you should look at using class instances to hold the data:

class Account{
    double checking;
    double saving;
public:
    int transactions();
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top