URGENT HELP NEEDED: Using Exception Handling to eliminate punctuation...

First, I want to preface this discussion with "I KNOW THERE IS AN EASIER WAY BESIDES EXCEPTION HANDLING!!" However, my assignment REQUIRES me to use exception handling in some way in my Mortgage calculator.

My code works!!....sort of....

It allows me to input the principal with a comma and it ignores the comma (eg. 200,000).

Then it allows me to input the number of years to be financed.

After that it returns -1.00 output with the rest of my code.

Output reads:

***************************
Welcome to ABC Bank!

How much are you wanting to finance?
200,000
Do you want a 15 or 30 year loan?
15
-1.00
Your monthly mortgage payment is -1.00 at an annual Interest rate of
3.28% for 15.00 years.


Process returned 0 (0x0) execution time : 7.644 s
Press any key to continue.
************************************

My question is where is the -1.00 coming from and how to I get the mortgage to calculate properly.

I have been writing and re-writing this for over 3 days now to figure out where my mistake is. My Professor is not answering my cries for help and neither are any of my classmates. This project is due TODAY!!!!!

I'm sitting on the edge of "screw it! Just turn it in broken!"

Please advise.

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <iomanip>
#include <string>
#include <cctype>
#include <exception>
#include <sstream>


using namespace std;

struct calcMortgage

{
    double Principal;
    double numYears;
    double IntRate;
    double monthlyPayments;
};

int main()
{
    calcMortgage myMortgage;

    cout <<" Welcome to ABC Bank! " <<endl <<endl;

    cout <<" How much are you wanting to finance?  " <<endl;

    {
    double retValue;
    std::string Principal;

     try
       {
        cin >> myMortgage.Principal;
       }
       catch(string Principal)      //Exception for comma in Principal input by user
       {
      if(Principal.find_first_not_of("0123456789.") != std::string::npos)
       {
       size_t pos;
       while((pos = Principal.find_first_not_of("0123456789.")) != std::string::npos)
       Principal.erase(pos, 1);
       }

    std::istringstream ins(Principal);    // Converts the string into a number without punctuation
    ins >> retValue;

    return retValue;

       }
    };

    cin >> myMortgage.Principal;

      if(!cin)
       {
        cin.clear();                              //Clears the error flags
        cin.ignore(1024, '\n');                   //Clears the input buffer
       }

       cout << " Do you want a 15 or 30 year loan? "<<endl;
       cin >> myMortgage.numYears;

     {
      if (myMortgage.numYears == 15)
        {
            myMortgage.IntRate=3.28;
        }
	 else
        {
            myMortgage.IntRate=4.03;
        }
     }
        double n = myMortgage.numYears*12;                            //n = Loan Length in months or number of payments
        double i = myMortgage.IntRate/1200;                           //i = interest rate times principal

       myMortgage.monthlyPayments=i*pow(1+i, n)*myMortgage.Principal/pow(1+i, n)-1;  //Formula for calculating monthly payments

      {
       if ((myMortgage.Principal/pow(1+i, n)-1)==0)                   //exception for 0 denominator condition
        {
            throw "Divide by zero condition in calculate payment method. Please check your numbers.";
        }
       else
        {
        (myMortgage.monthlyPayments=i*pow(1+i, n)*myMortgage.Principal/pow(1+i, n)-1);  //Formula for calculating monthly payments

        std::cout << std::fixed << std::setprecision(2) << myMortgage.monthlyPayments << std::endl;
        cout << "Your monthly mortgage payment is " << myMortgage.monthlyPayments << " at an annual Interest rate of "<< endl;
        cout << myMortgage.IntRate << "% for " << myMortgage.numYears << " years." << endl << endl;
        }
      }
    return 0;

}


Thanks - Mustang
closed account (SECMoG1T)
1
2
3
4
5
6
7
8
9
10
11
12
13
 try 
  {
      cin >> myMortgage.Principal;///are you sure an exemption was thrown here?
               /// are you sure if anything was read after after the ','  was encountered?
   }

  catch(string Principal) //does this sstring  contain anything at all?
 {
     if(Principal.find_first_not_of("0123456789.") != std::string::npos)
       {
           size_t pos; while((pos = Principal.find_first_not_of("0123456789.")) != std::string::npos)      
            Principal.erase(pos, 1);
   }
Last edited on
If you don't enter a comma, the calculation seems to be correct, except that you have to enter the financed amount twice.

How much are you wanting to finance? 
200000 
200000 
myMortgage.Principal is 200000 
Do you want a 15 or 30 year loan? 
15 
545.67 
Your monthly mortgage payment is 545.67 at an annual Interest rate of 3.28% for 15.00 years.


If you enter a comma, you're not getting a valid mortgage principal amount. I just added in a cout statement to output the principal amount in the struct.
How much are you wanting to finance? 
200,000 
myMortgage.Principal is 0 
Do you want a 15 or 30 year loan? 


The exception block is set off into its own scope, but it's not a separate function. What were you expecting to happen with line 50 return retValue;?

Last edited on
Andy and Wildblue -

I'm expecting the try/catch to remove the comma and just read the "200000" part of "200,000", then continue with the rest of the code execution.

WITH the comma, the code DOES allow me to input either 15 or 30 for the term of the loan. (This is also a good thing....to me.)

I need the code to ignore the comma, read the input as integer only, and calculate the correct monthly payments based on a 15 or 30 year loan.

I know I am on the right path, because the code works properly if I input "200000" without the comma.

I have made great progress over the last few days, but I just cannot seem to get to the "finish line". lol

Thanks for trying to help me.

Mustang
Andy1992 -

I fixed the fact that you have to enter the principal twice.

Now, the output is -0.45...closer??

Here's what I have now:
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <iomanip>
#include <string>
#include <cctype>
#include <exception>
#include <sstream>


using namespace std;

struct calcMortgage

{
    double Principal;
    double numYears;
    double IntRate;
    double monthlyPayments;
};

int main()
{
    calcMortgage myMortgage;

    cout <<" Welcome to ABC Bank! " <<endl <<endl;

    cout <<" How much are you wanting to finance?  " <<endl;

    {
    double retValue;
    std::string Principal;

     try
       {
        cin >> myMortgage.Principal;
       }
       catch(string Principal)      //Exception for comma in Principal input by user
       {
      if(Principal.find_first_not_of("0123456789.") != std::string::npos)
       {
       size_t pos; while((pos = Principal.find_first_not_of("0123456789.")) != std::string::npos)
       Principal.erase(pos, 1);
       }

    std::istringstream ins(Principal);    // Converts the string into a number without punctuation
    ins >> retValue;

    return retValue;

       }
    };

    int retValue;
    cin >> retValue;

      if(!cin)
       {
        cin.clear();                              //Clears the error flags
        cin.ignore(1024, '\n');                   //Clears the input buffer
       }

       cout << " Do you want a 15 or 30 year loan? "<<endl;
       cin >> myMortgage.numYears;

     {
      if (myMortgage.numYears == 15)
        {
            myMortgage.IntRate=3.28;
        }
	 else
        {
            myMortgage.IntRate=4.03;
        }
     }
        double n = myMortgage.numYears*12;                            //n = Loan Length in months or number of payments
        double i = myMortgage.IntRate/1200;                           //i = interest rate times principal

       myMortgage.monthlyPayments=i*pow(1+i, n)*myMortgage.Principal/pow(1+i, n)-1;  //Formula for calculating monthly payments

      {
       if ((myMortgage.Principal/pow(1+i, n)-1)==0)                   //exception for 0 denominator condition
        {
            throw "Divide by zero condition in calculate payment method. Please check your numbers.";
        }
       else
        {
        (myMortgage.monthlyPayments=i*pow(1+i, n)*myMortgage.Principal/pow(1+i, n)-1);  //Formula for calculating monthly payments

        std::cout << std::fixed << std::setprecision(2) << myMortgage.monthlyPayments << std::endl;
        cout << "Your monthly mortgage payment is " << myMortgage.monthlyPayments << " at an annual Interest rate of "<< endl;
        cout << myMortgage.IntRate << "% for " << myMortgage.numYears << " years." << endl << endl;
        }
      }
    return 0;

}


Still works properly when you don't use comma in principal input. :-)
closed account (SECMoG1T)
Well , the thing is am not convinced that your code will throw an exemption after reading a comma into double, at most an error state will be set " Failbit" will be set in your stream.

1
2
try { cin >> myMortgage.Principal; }///I think if we need to throw an exemption here, we rather change
 //this   
It's not throwing an exception - it reads in up to the comma.

1
2
3
4
5
    try
    {
        cin >> myMortgage.Principal;
        cout << "the try block principal is " << myMortgage.Principal << "\n";
    }


How much are you wanting to finance? 
200,000 
the try block principal is 200 
Do you want a 15 or 30 year loan? 

ok guys....

I don't know what to do anymore. I just had a major meltdown with this and I have given up.

I don't have the time it takes, as a beginner, to keep writing and rewriting this until I get it right.

I am overly frustrated and extremely exhausted from the late nights and early mornings trying to get this right.

Thanks so much for your efforts.

Mustang
closed account (SECMoG1T)
Check this out

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 try
  { 
      std::string exempt;
      std::stringstream ss; ss.clear ();
      cin >>exempt;

     if (exempt.find (',')==std::string::npos)
        ss <<exempt; 

      else
         throw exempt; 
       ss>> myMortgage.Principal; 
   }

   catch(string Principal) //Exception for comma in Principal input by user
  {
      if(Principal.find_first_not_of("0123456789.") != std::string::npos)
           { 
               size_t pos; 
         while((pos = Principal.find_first_not_of("0123456789.")) != std::string::npos) Principal.erase(pos, 1);   
          }
Last edited on
@ line 53

you don't need a semi colon (;) after the closing curly brace (}) of an inner block.

@ line 88

you shouldn't surround the variables (myMortgage.monthlyPayments ) assignment with parentheses.


try to avoid using inner blocks unless they are necessary.


|| Nazar Abdolkhani ||
Last edited on
Thanks Nezar.

Andy - then do I delete this portion of the code. It seems to read the same to me. Is it??

1
2
3
4
5
6
7
8
int retValue;
    cin >> retValue;

      if(!cin)
       {
        cin.clear();                              //Clears the error flags
        cin.ignore(1024, '\n');                   //Clears the input buffer
       }


Thanks ya'll
closed account (SECMoG1T)
Oh what is retValue supposed to do on line 55? give some detail, I hadn't seen it yet, I was caught up by your throw... dint proceed from there.
I thought it was supposed to reiterate the principal amount from the first portion of the code so the mortgage calculator would pull the correct number in order for the equation to work.

Cheers - Mustang
closed account (SECMoG1T)
1
2
3
4
5
6
7
8
9
10
11
12
13
ins >> retValue; /// line 47 , stream reads to a local variable retValue, when control exits the block on line 
///52 this variable is returned to main as an anonymous variable, and it's lost within that confusion... 
return retValue;// here

///Instead you should have read it into your object variable .
ins>>myMortgage.Principal;/// if you had done this, you have already stored your correct principal value 
///in your object variable, whether the exemption occured or not, both cases are taken care of
///: (my latest post line 12- takes care of the normal situation while this line above takes care of the 
///exemption), that's all you needed.

57- 61/// this lines requests the same value twice, @wildblue pointed that out, remove the code 
///between them, they aren't necessary, also remove any instance of "retValue" , you dont need it, remove the return on line 49 too. 
 


Hope that helps.
Last edited on
Andy - the code you shared with me sort of works...but it doesn't continue to the next cout statement and continue with the program.

It should then prompt me for the years and then calculate the monthly payment.

I'll try it without the aforementioned code.

Thanks - Mustang
closed account (SECMoG1T)
Did you remove line 49, i also told you to erase 54 - 61.
If you still get the bug, post the whole code again , i'll check it out.
Last edited on
Topic archived. No new replies allowed.