Solved

# Detect no input or 0, display only 2 decimal places

Posted on 2007-10-07
280 Views
Last Modified: 2010-04-01
Below is my mortgage program. I am having a couple of issues. The payment amount usually displays correctly, but in some cases it displays too many decimal places. If I use a loan of 10,000, 10 yrs, ad 9% iterest it displays 3 decimal places. I would like to make it always only display 2. Also, I am looking for a way to detect no input or 0, and display a message to try again. Any assistance would be appreciated.

My code

#include <cmath>
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

// function to validate loan amount and term
int read_int()
{

string s;
int n = 0;
char *pCnvEnd;

while (1)
{
cin >> s;
n = strtol(s.c_str(), &pCnvEnd, 10);
if (*pCnvEnd != NULL)
{
// invalid chars in string, not an integer
cout << "Not a valid number, please re-enter the value" << " ";
}
else
{
break; //valid, stop loop
}
}

return n;
}
// function to validate interest rate
double read_double()
{

string s;
double d = 0;
char *pCnvEnd;

while (1)
{
cin >> s;
d = strtod(s.c_str(), &pCnvEnd);
if (*pCnvEnd != NULL)
{
// invalid chars in string, not an integer
cout << "Not a valid number, please re-enter the value" << " ";
}
else
{
break; //valid, stop loop
}
}

return d;
}
// get user inputs and validate
void getInput(double &loanAmount, int &termYears, double &interestRate){

cout << "\t\t\tJon's Mortgage Calculator" << endl << endl;
// Calculator Title
cout << "\n\n \t\t\t Loan amount: \$"; // ask user for loan amount
loanAmount = read_double(); // capture loan amount
cout << "\n\n \t\t\t Loan Term In Years: "; // ask user for loan term
termYears = read_int(); // capture loan term
cout << "\n\n \t\t\t Yearly Interest Rate: "; // ask user for interest rate
interestRate = read_double(); // capture interest rate

}

// function to print amortization table
void printLoanPayments(int payment, double loanBalance, double monthlyPrinciple, double monthlyInterest){
// print verbage and data values
cout << " " << setw(15) << setprecision(2) << payment;
cout << " " << setw(15) << fixed << setprecision(2) << fabs(loanBalance);
cout << " " << setw(15) << fixed << setprecision(2) << monthlyPrinciple;
cout << setw(15) << fixed << setprecision(2) << monthlyInterest << endl;
}

void computeMortgage(double &loanAmount, int &termYears, double &interestRate){
int payment = 0; // payment incrementor
int termMonths; // term in months
double monthlyPayment; // monthly payment

double monthlyInterest; // vaiable to hold monthly interest paid
double loanBalance; // variable to hold descending loan balance
int months = 0; // month incrementor
double monthlyPrinciple; // variable to hold monthly principle paid
int lineCount = 1; // variable to count lines for screen pause
double interestRateMonthly; //

//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 +
interestRateMonthly), termMonths));

//display monthly payment to the screen.
cout << "\n\n \t\t\t Monthly Payment \$" << monthlyPayment  << endl << endl;

loanBalance = loanAmount; // set initial loan balance to loan amount

// create headings and separator line
cout << "\t Payment Number" << "\t Loan Balance" << "\t Principle Paid" << "\t Interest Paid" << endl;
cout << "\t -------------------------------------------------------------" << endl;

while (loanBalance >= 0.01) //Loop ends when loan is below one penny

{
monthlyInterest = (loanBalance *interestRateMonthly);
// calculate monthly interest
monthlyPrinciple = monthlyPayment - monthlyInterest;
// calculate monthly principle
loanBalance = loanBalance - monthlyPrinciple; // calculate loan balance
loanAmount = loanBalance; // assign new balance ot loan amount
payment++; // increment payment number

// print verbage and data values
printLoanPayments(payment, loanBalance, monthlyPrinciple, monthlyInterest);

loanBalance = loanAmount; // assign remaining balance to loan balance
lineCount++; // increment line counter

// count for payment printed to screen
if (lineCount > 20)
{
//pause displays a message and waits for the user to hit a key
system("PAUSE");
lineCount = 0; // Reset line counter

// reprint headings
cout << "\t Payment Number" << "\t Loan Balance" << "\t Principle Paid" << "\t Interest Paid" << endl;
cout << "\t -------------------------------------------------------------" << endl;

}
}
}
int main()
{

//declare variables

double loanAmount; // loan amount
double interestRate; // interest rate
char again = '0'; // NOT int again = 0;
int termYears; // term of loan in years
do
// Loop to allow the user another calculation
{
getInput(loanAmount, termYears,interestRate);
computeMortgage(loanAmount,termYears,interestRate);
// Offer the user another calculation
cout << (
"\n\n\t Enter 1 to calculate another mortgage, any other key to quit ");
cin >> again; // capture response for another calculation
system("cls"); // clear the screen
}
while (again == '1') // End of loop for another go.
;

return 0;
}
0
Question by:ghost8067
12 Comments

LVL 53

Assisted Solution

If you want to limit it to two decimal places, you can use  << fixed << setprecision(2) just like you did elsewhere in the code.
0

LVL 86

Expert Comment

And to detect '0', test for that value in your input function:

// function to validate loan amount and term
int read_int()
{

string s;
int n = 0;
char *pCnvEnd;

while (1)
{
cin >> s;
n = strtol(s.c_str(), &pCnvEnd, 10);
if (*pCnvEnd != NULL)
{
// invalid chars in string, not an integer
cout << "Not a valid number, please re-enter the value" << " ";
}
else
{
if (n == 0)
cout << "Not a valid number, please re-enter a non-null value" << " ";
else break; //valid and non-zero input, stop loop <------------------
}
}
0

LVL 7

Expert Comment

For detecting no input or 0, you will need to write function

int getNumbet();

that read char by char until the end of line.
Then trim string read in that way.
If the result is "0" or "" that function should return some special value (for example negative value).
else it should return read value converted from string to int.

If you need more help on this, just ask.
0

Author Comment

Thanks, that worked fine. I was forgetting to include the fixed statement.
0

Author Comment

I now have a successful check for 0's on all 3 fields ad the decimal displaying 2 places. If ayone has an idea to detect nothing entered, it would be appreciated.
0

LVL 86

Expert Comment

That would be

// function to validate loan amount and term
int read_int()
{

string s;
int n = 0;
char *pCnvEnd;

while (1)
{
cin >> s;
n = strtol(s.c_str(), &pCnvEnd, 10);
if (*pCnvEnd != NULL || 0 == s.length()) // check for "nothing" also
{
// invalid chars in string, not an integer
cout << "Not a valid number, please re-enter the value" << " ";
}
else
{
if (n == 0)
cout << "Not a valid number, please re-enter a non-null value" << " ";
else break; //valid and non-zero input, stop loop <------------------
}
}
0

Author Comment

I gave that a try. Cursor sits there as before without displaying the error message. The code is below

#include <cmath>
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

// function to validate loan amount and term
int read_int()
{

string s;
int n = 0;
char *pCnvEnd;

while (1)
{
cin >> s;
n = strtol(s.c_str(), &pCnvEnd, 10);
if (*pCnvEnd != NULL || 0 == s.length()) // check for "nothing" also

{
// invalid chars in string, not an integer
cout << "Not a valid number, please re-enter the value" << " ";
}
else
{
if (n == 0)
cout << "Please enter a non-zero value " << " ";
else break; //valid and non-zero input, stop loop <------------------
}
}
return n;
}
// function to validate interest rate
double read_double()
{

string s;
double d = 0;
char *pCnvEnd;

while (1)
{
cin >> s;
d = strtod(s.c_str(), &pCnvEnd);
if (*pCnvEnd != NULL || 0 == s.length()) // check for "nothing" also

{
// invalid chars in string, not an integer
cout << "Not a valid number, please re-enter the value" << " ";
}
else
{
if (d == 0)
cout << "Please enter a non-zero value " << " ";
else break; //valid and non-zero input, stop loop <------------------

}
}

return d;
}
// get user inputs and validate
void getInput(double &loanAmount, int &termYears, double &interestRate){

cout << "\t\t\tJon's Mortgage Calculator" << endl << endl;
// Calculator Title
cout << "\n\n \t\t\t Loan amount: \$"; // ask user for loan amount
loanAmount = read_int(); // capture loan amount
cout << "\n\n \t\t\t Loan Term In Years: "; // ask user for loan term
termYears = read_int(); // capture loan term
cout << "\n\n \t\t\t Yearly Interest Rate: "; // ask user for interest rate
interestRate = read_double(); // capture interest rate

}

// function to print amortization table
void printLoanPayments(int payment, double loanBalance, double monthlyPrinciple, double monthlyInterest){
// print verbage and data values
cout << " " << setw(15) << setprecision(2) << payment;
cout << " " << setw(15) << fixed << setprecision(2) << fabs(loanBalance);
cout << " " << setw(15) << fixed << setprecision(2) << monthlyPrinciple;
cout << setw(15) << fixed << setprecision(2) << monthlyInterest << endl;
}

void computeMortgage(double &loanAmount, int &termYears, double &interestRate){
int payment = 0; // payment incrementor
int termMonths; // term in months
double monthlyPayment; // monthly payment

double monthlyInterest; // vaiable to hold monthly interest paid
double loanBalance; // variable to hold descending loan balance
int months = 0; // month incrementor
double monthlyPrinciple; // variable to hold monthly principle paid
int lineCount = 1; // variable to count lines for screen pause
double interestRateMonthly; //

//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 +
interestRateMonthly), termMonths));

//display monthly payment to the screen.
cout << "\n\n \t\t\t Monthly Payment \$" << fixed << setprecision(2) << monthlyPayment  << endl << endl;

loanBalance = loanAmount; // set initial loan balance to loan amount

// create headings and separator line
cout << "\t Payment Number" << "\t Loan Balance" << "\t Principle Paid" << "\t Interest Paid" << endl;
cout << "\t -------------------------------------------------------------" << endl;

while (loanBalance >= 0.01) //Loop ends when loan is below one penny

{
monthlyInterest = (loanBalance *interestRateMonthly);
// calculate monthly interest
monthlyPrinciple = monthlyPayment - monthlyInterest;
// calculate monthly principle
loanBalance = loanBalance - monthlyPrinciple; // calculate loan balance
loanAmount = loanBalance; // assign new balance ot loan amount
payment++; // increment payment number

// print verbage and data values
printLoanPayments(payment, loanBalance, monthlyPrinciple, monthlyInterest);

loanBalance = loanAmount; // assign remaining balance to loan balance
lineCount++; // increment line counter

// count for payment printed to screen
if (lineCount > 20)
{
//pause displays a message and waits for the user to hit a key
system("PAUSE");
lineCount = 0; // Reset line counter

// reprint headings
cout << "\t Payment Number" << "\t Loan Balance" << "\t Principle Paid" << "\t Interest Paid" << endl;
cout << "\t -------------------------------------------------------------" << endl;

}
}
}
int main()
{

//declare variables

double loanAmount; // loan amount
double interestRate; // interest rate
char again = '0'; // NOT int again = 0;
int termYears; // term of loan in years
do
// Loop to allow the user another calculation
{
getInput(loanAmount, termYears,interestRate);
computeMortgage(loanAmount,termYears,interestRate);
// Offer the user another calculation
cout << (
"\n\n\t Enter 1 to calculate another mortgage, any other key to quit ");
cin >> again; // capture response for another calculation
system("cls"); // clear the screen
}
while (again == '1') // End of loop for another go.
;

return 0;
}
0

Author Comment

Sorry, I posted the old code. Here it is with the changes.

#include <cmath>
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

// function to validate loan amount and term
int read_int()
{

string s;
int n = 0;
char *pCnvEnd;

while (1)
{
cin >> s;
n = strtol(s.c_str(), &pCnvEnd, 10);
if (*pCnvEnd != NULL || 0 == s.length()) // check for "nothing" also

{
// invalid chars in string, not an integer
cout << "Not a valid number, please re-enter the value" << " ";
}
else
{
if (n == 0)
cout << "Please enter a non-zero value " << " ";
else break; //valid and non-zero input, stop loop <------------------
}
}
return n;
}
// function to validate interest rate
double read_double()
{

string s;
double d = 0;
char *pCnvEnd;

while (1)
{
cin >> s;
d = strtod(s.c_str(), &pCnvEnd);
if (*pCnvEnd != NULL || 0 == s.length()) // check for "nothing" also

{
// invalid chars in string, not an integer
cout << "Not a valid number, please re-enter the value" << " ";
}
else
{
if (d == 0)
cout << "Please enter a non-zero value " << " ";
else break; //valid and non-zero input, stop loop <------------------

}
}

return d;
}
// get user inputs and validate
void getInput(double &loanAmount, int &termYears, double &interestRate){

cout << "\t\t\tJon's Mortgage Calculator" << endl << endl;
// Calculator Title
cout << "\n\n \t\t\t Loan amount: \$"; // ask user for loan amount
loanAmount = read_int(); // capture loan amount
cout << "\n\n \t\t\t Loan Term In Years: "; // ask user for loan term
termYears = read_int(); // capture loan term
cout << "\n\n \t\t\t Yearly Interest Rate: "; // ask user for interest rate
interestRate = read_double(); // capture interest rate

}

// function to print amortization table
void printLoanPayments(int payment, double loanBalance, double monthlyPrinciple, double monthlyInterest){
// print verbage and data values
cout << " " << setw(15) << setprecision(2) << payment;
cout << " " << setw(15) << fixed << setprecision(2) << fabs(loanBalance);
cout << " " << setw(15) << fixed << setprecision(2) << monthlyPrinciple;
cout << setw(15) << fixed << setprecision(2) << monthlyInterest << endl;
}

void computeMortgage(double &loanAmount, int &termYears, double &interestRate){
int payment = 0; // payment incrementor
int termMonths; // term in months
double monthlyPayment; // monthly payment

double monthlyInterest; // vaiable to hold monthly interest paid
double loanBalance; // variable to hold descending loan balance
int months = 0; // month incrementor
double monthlyPrinciple; // variable to hold monthly principle paid
int lineCount = 1; // variable to count lines for screen pause
double interestRateMonthly; //

//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 +
interestRateMonthly), termMonths));

//display monthly payment to the screen.
cout << "\n\n \t\t\t Monthly Payment \$" << fixed << setprecision(2) << monthlyPayment  << endl << endl;

loanBalance = loanAmount; // set initial loan balance to loan amount

// create headings and separator line
cout << "\t Payment Number" << "\t Loan Balance" << "\t Principle Paid" << "\t Interest Paid" << endl;
cout << "\t -------------------------------------------------------------" << endl;

while (loanBalance >= 0.01) //Loop ends when loan is below one penny

{
monthlyInterest = (loanBalance *interestRateMonthly);
// calculate monthly interest
monthlyPrinciple = monthlyPayment - monthlyInterest;
// calculate monthly principle
loanBalance = loanBalance - monthlyPrinciple; // calculate loan balance
loanAmount = loanBalance; // assign new balance ot loan amount
payment++; // increment payment number

// print verbage and data values
printLoanPayments(payment, loanBalance, monthlyPrinciple, monthlyInterest);

loanBalance = loanAmount; // assign remaining balance to loan balance
lineCount++; // increment line counter

// count for payment printed to screen
if (lineCount > 20)
{
//pause displays a message and waits for the user to hit a key
system("PAUSE");
lineCount = 0; // Reset line counter

// reprint headings
cout << "\t Payment Number" << "\t Loan Balance" << "\t Principle Paid" << "\t Interest Paid" << endl;
cout << "\t -------------------------------------------------------------" << endl;

}
}
}
int main()
{

//declare variables

double loanAmount; // loan amount
double interestRate; // interest rate
char again = '0'; // NOT int again = 0;
int termYears; // term of loan in years
do
// Loop to allow the user another calculation
{
getInput(loanAmount, termYears,interestRate);
computeMortgage(loanAmount,termYears,interestRate);
// Offer the user another calculation
cout << (
"\n\n\t Enter 1 to calculate another mortgage, any other key to quit ");
cin >> again; // capture response for another calculation
system("cls"); // clear the screen
}
while (again == '1') // End of loop for another go.
;

return 0;
}
0

LVL 86

Expert Comment

Um, I forgot, 'cin' won't let you enter an empty string anyway...
0

LVL 86

Accepted Solution

Hm, try

getline(cin,s);

instead of

cin >> s;
0

Author Comment

Thanks for the help. I gave more of the points to jkr. It was the more difficult problem of the 2 .
0

LVL 53

Expert Comment

>> I gave more of the points to jkr. It was the more difficult problem of the 2 .

No problem - he deserves it. For some reason, I missed your second question - otherwise I would have answered it too heh. I need new glasses ;)
0

## Write Comment

Please enter a first name

Please enter a last name

We will never share this with anyone.

## Featured Post

C++ Properties One feature missing from standard C++ that you will find in many other Object Oriented Programming languages is something called a Property (http://www.experts-exchange.com/Programming/Languages/CPP/A_3912-Object-Properties-in-C.ht…
This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

#### 779 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

#### Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!