Iterate through a vector

The function should iterate through the vector listAccounts of type Account.
And if the account_name in listAccounts = name, the balance of that element should be updated.

But in this code the if statement is just skipped, and it goes straight to:
cout << "account does not exist""\n";

1
2
3
4
5
6
7
8
9
10
11
void Account::change_balance(string name, int balance) {

    for(auto& account : listAccounts) {
        if(account.account_name == name) {
            account.account_balance = balance + account.account_balance;
            cout << account.account_balance;
            return;
        }
    }
    cout << "account does not exist""\n";
}


I can't figure out what I'm doing wrong?
Last edited on
What do you mean by "skipped"?

How about a debug printout:
1
2
3
4
5
6
7
8
9
10
11
12
void Account::change_balance(string name, int balance) {
    cout << listAccounts.size() << " accounts to check\n";
    for(auto& account : listAccounts) {
        cout << "Testing '" << account.account_name << "' against '" << name "'\n";
        if(account.account_name == name) {
            account.account_balance += balance;
            cout << account.account_balance;
            return;
        }
    }
    cout << "account does not exist""\n";
}
Last edited on
Thanks!

So I did that, and I got "0 accounts to check"

Is this a problem with pushback into my vector?

By skipped I meant that even if: account.account_name == name
the balance wouldn't be changed, nor would the new balance be printed.


This is the function where I pushback into the vector:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void Account::init_account(string name, char type) {

        Account account;
        
        if (type == 'y') {
            account.account_type = 1;
        } else if (type == 'n') {
            account.account_type = 0;
        }

        account.account_name = name;
        account.account_balance = 0;

        listAccounts.push_back(account);

}


The same function is called every time the user enters 'create' in main.
and the change_balance function is called evey time the user enters 'transaction' in main.

Am I doing something wrong?
Last edited on
Topic archived. No new replies allowed.