Urgent help && || with do-while loop and bank account

User can't withdraw more than what's available or withdraw a negative amount.(i have a deposit function for this already). The && or || is confusing me more than it should be :/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void BankAccount::withdraw(double amount){
	do
	{
		cout << "How much would you like to withdraw?" << endl;
		cin >> amount;
		if ((amount <= bal) && (amount > 0)) {
			  bal -= amount;
			  cout << "Balance is: $" << bal << endl;
		   } else {
			  cout << "Can't overdraw/withdraw negative/zero amount." << endl;
			  cout << "Available balance is: $" << bal << endl;
		   }
	}
	while ((amount >= bal) && (amount > 0));

}


Inputting 500 when there's a balance of 255.35, outputs:


1
2
Can't overdraw/withdraw negative/zero amount.
Available balance is: $255.35 


Then immediately ends when I want it to repeat for a valid input.
Line 14: Your logic is backwards. You're saying you want to loop while both conditions are true (amount is valid). You want to loop while amount is NOT valid.
 
  while (! (amount >= bal && amount > 0));


Line 1: Why is amount an argument? It should be a local variable.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void BankAccount::withdraw() {

	double amount = 0;
	while (true) {

		std::cout << "Enter amount to withdraw: ";
		std::cin >> amount;

		if ((amount > 0) && (amount <= balance)) {
			break;
		}
		//Error message

	}

	balance -= amount;
	std::cout << "New balance: " << balance << std::endl;

}
@ AbstractionAnon

Sorry this code was a snippet of my program. I should've copied the entire code.

@ xismn

Thanks! Bad habit of mine to continue using what I *think* I know instead of using another method, such as while(true).

Code is working exactly as I wanted.

Thanks you guys :)
this code was a snippet of my program

I understand that. What i was trying to say is that amount should NOT have been an argument. Declaring amount as an argument implies that withdrawal() can be called passing an amount to be withdrawn. That is not how the function works. Note that xismn removed amount as an argument and properly declared it as a local variable.
Topic archived. No new replies allowed.