Help with Do..While and If..

My code seems to be functioning properly but I can't seem to be able to make the terminating part pop up along with "-1" in the program when I input it. It keeps popping up with a null value after the "$" sign at the end.

Loan range: $10000 - $100000]
Enter loan amount (-1 to quit): $

As I said earlier, I've tried doing everything but I can't seem to make terminating part pop up with "-1".

**************************************

Here's my code

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
double loanamt = 0;
double depamt = 0;

cout << "[Loan range: $10000 - $100000]" << endl;
cout << "Enter loan amount (-1 to quit): $";
do
{
cin >> loanamt;
{
if (loanamt == 0)
cout << "\nEnter loan amount (-1 to quit): $";
else if
(loanamt < 10000 || loanamt > 100000)
cout << "\nInvalid loan amount!\nPlease re-enter the loan amount: RM";
}
}
while (loanamt != -1);




return 0;
}
Last edited on
The problem is that if loanamt is -1, then loanamt < 10000 is true, so it prints Invalid load amount. At the bottom of the loop it decides to terminate.

One way to handle this is to change the loop to a while loop and check for -1 when you read the number.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <iomanip>

using namespace std;

int
main()
{
    //Assigning ***insert name of it
    double loanamt = 0;
    double depamt = 0;

    cout << "[Loan range: $10000 - $100000]" << endl;
    cout << "Enter loan amount (-1 to quit): $";
    while ((cin >> loanamt) && loanamt != -1) {
	if (loanamt < 10000 || loanamt > 100000)
	    cout << "\nInvalid loan amount!\nPlease re-enter the loan amount: $";
	else
	    cout << "\nEnter loan amount (-1 to quit): $";
    }

    cout << "\nTerminating program... " << endl;

    return 0;
}

Ah, thank you so much! I think I understand how it works now. While seems easier to work with than do while.

I've got the program to run now. Once again, thank you :D
Topic archived. No new replies allowed.