Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Problem with strtof function and validating a double

Posted on 2007-10-01
10
Medium Priority
?
1,240 Views
Last Modified: 2008-01-09
I am having trouble with the strtof function in my porrogram. I want to use it to validate a vaild double was entered. I am vaidating the mortgage amount and the loan term in the read_int function. I want to do a similar thing in the read_double function below it. I am getting the following errors when I try to compile.

mortgage2func\mortgage2func.cpp(56) : error C3861: 'strtof': identifier not found
mortgage2func.cpp(64) : warning C4244: 'return' : conversion from 'double' to 'int', possible loss of data

I also am sure I have something wrong in the way I am trying to validate the double.
Any assistance would be appreciated.

/*  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
@version 2.0
Changes for this version - Program altered to accept loan terms rather
than having them hard coded as in the previous version. Program removed
from main and multiple functions created. Validation for any bad characters
user entered data added for loan amount and term.
 */


#include <cmath>
#include <iostream>
#include <stdio.h>
#include <conio.h>
#include <string>
#include <stdlib.h>

using namespace std;

void printtitle()
{
  //Print blank line followed by title
  cout << endl; // add blank line before title.
  cout << "\t\t\tJon's Mortgage Calculator" << endl << endl; // Calculator Title
}

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;
}

int read_double() {

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

  while(1) {
    cin >> s;
    d = strtof(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 d;
}


double getloanamount()
{
  double l = 0.00;
  while (l <= 0.00)
  //check for positive value
  {
    cout << "\n\n \t\t\t Loan amount: $"; // ask user for loan amount
      l = read_int();
  }
  return l;
}

int getterm()
{
  int t = 0;
  while (t <= 0)
  //check for positive value
  {
    cout << "\n      \n \t\t\t Loan Term In Years: "; // ask user for loan term
      t = read_int();
  }
  return t;
}

double getinterestrate()
{
  double i = 0;
  while (i <= 0)
  //check for positive value
  {
    cout << "\n\n \t\t\t Yearly Interest Rate: "; // ask user for interest rate
    //cin >> i; // capture interest rate
      i = read_double();
  }
  return i;
}

int calctermmonths(int a)
{
  int m;
  {
    m = (a *12);
  }
  return m;
}

double calcmonthlyrate(double a)
{
  double mr;
  {
    mr = ((a / 12) / 100);
  }
  return mr;
}

double calcmonthlypayment(double a, double b, int c)
{
  double payment;
  {
    payment = (a *b) / (1-pow(1.0 / (1.0 + b), c));

  }
  return payment;
}

double printpayment(double a)
{
  {
    cout << "\n\n \t\t\t Monthly Payment $" << a << endl << endl;
  }
  return a;
}

char offernewmortgage()
{
  char newmortgage = 'N';
  {
    cout << (
      "\n\n\t Enter Y or y to calculate another mortgage, any other key to quit  ");
    newmortgage = _getch(); // capture response for another calculation                                          
    system("cls"); // clear the screen

  }
  return newmortgage;
}


int calcmortgage()
{
  //declare variables

  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;
  do
  {
    loanAmount = 0.00;
    termYears = 0;
    interestRate = 0.00;

    printtitle();
    loanAmount = getloanamount();
    termYears = getterm();
    interestRate = getinterestrate();
    termMonths = calctermmonths(termYears);
    interestRateMonthly = calcmonthlyrate(interestRate);
    monthlyPayment = calcmonthlypayment(loanAmount, interestRateMonthly,
      termMonths);
    printpayment(monthlyPayment);
    again = offernewmortgage();
  }
  while (again == 'Y' || again == 'y'); // End of loop for another go.

  system("PAUSE") ;
    return 0;
}



int main()
{
  int iret = calcmortgage();

  return iret;
 
}
0
Comment
Question by:ghost8067
  • 5
  • 4
10 Comments
 
LVL 22

Expert Comment

by:grg99
ID: 19992338
strtof() should be defined in   #include <stdlib.h>

the fact that it's not is a bit disturbing.

You might try the similar fscanf( ),  hope that's around!

something like:    fscanf( stdin, "%Lf", &TheDouble );
0
 
LVL 86

Expert Comment

by:jkr
ID: 19992351
Did you  mean 'strtod()' or 'atof()'? There is no 'strtof()' function
0
 

Author Comment

by:ghost8067
ID: 19992576
It was recommended in another question I answered. I also found it at http://www.codecogs.com/reference/stdlib.h/strtod.php?alias=strtof

Anyway, is there one you recommend for validating the value?
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 86

Expert Comment

by:jkr
ID: 19992594
VC++ only has 'strtod()' - just rename the call to

  while(1) {
    cin >> s;
    d = strtod(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
    }
  }

and you are fine.
0
 

Author Comment

by:ghost8067
ID: 19992619
Okay, I gave that a try. It compiles, but when I enter a loan it comes up with the wrong answer. I did a display on i in  getinterestrate(), ande got a 5 rather than 5.75. That is what is throwing off the calculation.
Any suggestions?
0
 

Author Comment

by:ghost8067
ID: 19992649
By the way, I had to remove &pCnvEnd,10, as it gave a compiler error.
0
 
LVL 86

Expert Comment

by:jkr
ID: 19992659
You need to avoid using integers when caclulation floating point values. I.e. make

    mr = ((a / 12) / 100);

read

     mr = ((a / 12.0) / 100.0);

to avoid these  problems.
0
 

Author Comment

by:ghost8067
ID: 19992715
The change didn't seem to help. The value returned is still an int. If I enter 5.75, 5 gets passed back. The updated code is below.

/*  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
@version 2.0
Changes for this version - Program altered to accept loan terms rather
than having them hard coded as in the previous version. Program removed
from main and multiple functions created. Validation for any bad characters
user entered data added for loan amount and term.
 */


#include <cmath>
#include <iostream>
#include <stdio.h>
#include <conio.h>
#include <string>
#include <stdlib.h>

using namespace std;

void printtitle()
{
  //Print blank line followed by title
  cout << endl; // add blank line before title.
  cout << "\t\t\tJon's Mortgage Calculator" << endl << endl; // Calculator Title
}

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;
}

int 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;
}


double getloanamount()
{
  double l = 0.00;
  while (l <= 0.00)
  //check for positive value
  {
    cout << "\n\n \t\t\t Loan amount: $"; // ask user for loan amount
      l = read_int();
  }
  return l;
}

int getterm()
{
  int t = 0;
  while (t <= 0)
  //check for positive value
  {
    cout << "\n      \n \t\t\t Loan Term In Years: "; // ask user for loan term
      t = read_int();
  }
  return t;
}

double getinterestrate()
{
  double i = 0;      
  while (i <= 0)
  //check for positive value
  {
    cout << "\n\n \t\t\t Yearly Interest Rate: "; // ask user for interest rate
    //cin >> i; // capture interest rate
      i = read_double();
      cout << i;
  }
  return i;
}

int calctermmonths(int a)
{
  int m;
  {
    m = (a *12);
  }
  return m;
}

double calcmonthlyrate(double a)
{
  double mr;
  {
    mr = ((a / 12.0) / 100.0);
  }
  return mr;
}

double calcmonthlypayment(double a, double b, int c)
{
  double payment;
  {
    payment = (a *b) / (1-pow(1.0 / (1.0 + b), c));

  }
  return payment;
}

double printpayment(double a)
{
  {
    cout << "\n\n \t\t\t Monthly Payment $" << a << endl << endl;
  }
  return a;
}

char offernewmortgage()
{
  char newmortgage = 'N';
  {
    cout << (
      "\n\n\t Enter Y or y to calculate another mortgage, any other key to quit  ");
    newmortgage = _getch(); // capture response for another calculation                                          
    system("cls"); // clear the screen

  }
  return newmortgage;
}


int calcmortgage()
{
  //declare variables

  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;
  do
  {
    loanAmount = 0.00;
    termYears = 0;
    interestRate = 0.00;

    printtitle();
    loanAmount = getloanamount();
    termYears = getterm();
    interestRate = getinterestrate();
    termMonths = calctermmonths(termYears);
    interestRateMonthly = calcmonthlyrate(interestRate);
    monthlyPayment = calcmonthlypayment(loanAmount, interestRateMonthly,
      termMonths);
    printpayment(monthlyPayment);
    again = offernewmortgage();
  }
  while (again == 'Y' || again == 'y'); // End of loop for another go.

  system("PAUSE") ;
    return 0;
}



int main()
{
  int iret = calcmortgage();

  return iret;
 
}
0
 
LVL 86

Accepted Solution

by:
jkr earned 2000 total points
ID: 19992774
Look at the declaration:

int 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;
}

That should be

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;
}
0
 

Author Comment

by:ghost8067
ID: 19992819
You are excellent!  Works like a charm.
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
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…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
Suggested Courses

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

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

Join & Ask a Question