Ask for a value again if user does not enter anything
Posted on 2007-09-30
I have created the mortgage calculatir below. Everything works fine, except if the user does not enter a value and hits enter, my while statement does not catch it. How can I code so that if the user does not enter a value, I ask for it again as it works if they enter a 0.
/* This program will accept the loan amount, The term of the loan, and the
interest rate and display the monthly payment to the screen. The user
will then be offered the choice of running another loan or quitting.
@author Jon Schab
Changes for this version - Program altered to accept loan terms rather
than having them hard coded as in the previous version.
using namespace std;
double loanAmount; // loan amount
double interestRate; // interest rate
double interestRateMonthly; // monthly interest rate
int termYears; // term of loan in years
int termMonths; // term in months
double monthlyPayment; // monthly payment
char again = 'N'; // NOT char again = Y;
// Loop to allow the user another calculation
// reset fields for anpother mortgage
loanAmount = 0.00;
termYears = 0;
interestRate = 0.00;
//display questions and recieve input from user.
cout << endl; // add blank line before title.
cout << "\t\t\tJon's Mortgage Calculator" << endl << endl; // Calculator Title
while(loanAmount <= 0.00) //check for positive value
cout << "\n\n \t\t\t Loan amount: $"; // ask user for loan amount
cin >> loanAmount;
while(termYears <= 0) //check for positive value
cout << "\n \n \t\t\t Loan Term In Years: "; // ask user for loan term
cin >> termYears; // capture loan term
while(interestRate <= 0) //check for positive value
cout << "\n\n \t\t\t Yearly Interest Rate: "; // ask user for interest rate
cin >> interestRate; // capture interest rate
//calculate term in years and monthly interest rate
interestRateMonthly = ((interestRate / 12) / 100);
termMonths = (termYears *12);
//calculate mothly payment
monthlyPayment = (loanAmount *interestRateMonthly) / (1 - pow(1.0 / (1.0 +
//display terms and monthly payment to the screen.
cout << "\n\n \t\t\t Monthly Payment $" << monthlyPayment << endl << endl;
// Offer the user another calculation
cout << (
"\n\n\t Enter Y or y to calculate another mortgage, any other key to quit ");
again = _getch(); // capture response for another calculation
system("cls"); // clear the screen
while (again == 'Y' || again == 'y'); // End of loop for another go.