Hi All,
I am having problems with reading input from a sequetail file and I can't figure out what is wrong. Can someone please help me out, I don't know if I am even doing it right, very new at this.
The code below is how I generated my .txt file or maybe I should have just opened word, put in the numbers and just saved it as a .txt file. I don't know but want to include all that I did. I had to use term1, term2, term3, ect. before it would put all the values into my .txt file, maybe this is part of my problem also.
// Fig. 17.25: MC CreateSequentialFile.cpp
// Create a sequential file.
#include <iostream>
using std::cerr;
using std::cin;
using std::cout;
using std::endl;
using std::ios;
#include <fstream> // file stream
using std::ofstream; // output file stream
#include <cstdlib>
using std::exit; // exit function prototype
int main()
{
// ofstream constructor opens file
ofstream outMCSequentialFile( "calculations.txt", ios::out );
// exit program if unable to create file
if ( !outMCSequentialFile ) // overloaded ! operator
{
cerr << "File could not be opened" << endl;
exit( 1 );
} // end if
cout << "Please enter term in years." << endl;
double term1;
double term2;
double term3;
// read different terms from cin, then place in file
cin >> term1 >> term2 >> term3;
{
outMCSequentialFile << term1 << ' ' << term2 << ' ' << term3 << endl;
cout << "? ";
} // end while
cout << "Enter Interest Rate." << endl
<< "Enter end-of-file to end input.\n? ";
double intRate1;
double intRate2;
double intRate3;
// read interest rates from cin, then place in file
cin >> intRate1>> intRate2 >> intRate3;
{
outMCSequentialFile << intRate1 << ' ' << intRate2 << ' ' << intRate3 << endl;
cout << "? ";
} // end while
return 0; // ofstream destructor closes file
} // end main
My array table:
7 15 30
5.35 5.5 5.75
Below is my main program. If I enter menu selection 1 the program works just like it should and all is fine there. It's when I enter menu selection 2 that I have all the problems.
I can't get it to display the payent amount or the amortization table at all. Like I said, I really don't know how to do this but have to learn, it seems like C++ is a good progaming language but learning it has been hard for me.
/* Week 4 Individual Assignment
PRG 411
Written By: Ken Volkman
Date: 09/06/2008
File Name: MC_PRG411_WK4
Purpose: To calculate the amount a Mortgage Payement will be from
user input values and to show the amortization schedule. Also it will let
the user to select from a pre-determined menu of rates.
*/
#include <iostream> // Library defines facilities for basic I/O operations...
#include <iomanip> // Libaray for stream manipulators...
#include <string> // Library for accepting stings...
#include <limits> // Library for setting limits...
#include <cmath>
#include <fstream>
#include <stdlib.h>
using namespace std; // Standard using definitions...
class MortgageCal
{
private:
double intYear; // interest rate per year...
double intMonth; // interest converted to months...
double loanAmt; // amount of the loan...
double term; // term in years...
double numMonths; // term converted to months...
double paymentAmt; // variable for monthly payment...
double balance; // running total...
double principleAmt;// amount towards loan...
double loanBal;
public:
// Constructor, initializes any unpassed value to zero...
MortgageCal(
double intYear = 0,
double term = 0,
double loanAmt = 0,
double paymentAmt = 0,
double numMonths = 0,
double intMonth = 0,
double balance = 0,
double principleAmt = 0,
double loanBal = 0):
intYear(intYear),
term(term),
loanAmt(loanAmt),
paymentAmt(paymentAmt),
numMonths(),
intMonth(),
balance(),
principleAmt(),
loanBal(){ }
/// get and set for data elements...
double getnumMonths() { return term * 12; }
bool setnumMonths(double months)
{
if (months > 0) { term = months/12; }
else { return false; }
return true;
}
double getTermInYears() { return term; }
bool setTermInYears(double years)
{
if (years > 0) { term = years; }
else { return false; }
return true;
}
double getPrinciple() { return principleAmt;}
bool setPrinciple(double principle)
{
if (principle >= 0) { principleAmt = principle; }
else { return false; }
return true;
}
double getLoanAmount(){ return loanAmt; }
bool setLoanAmount(double loan)
{
if (loan >= 0) { loanAmt = loan; }
else { return false; }
return true;
}
double getYearlyRate() { return intYear; }
bool setYearlyRate(double rate)
{
intYear = rate;
return true;
}
double getPaymentAmount() { return paymentAmt; }
bool setPaymentAmount (double payment)
{
return true;
}
double getLoanBalance() { return loanBal;}
bool setLoanBalance(double loanB)
{
if (loanB >= 0) { loanBal = loanBal-principleAmt; }
else { return false; }
return true;
}
double getInterestMonth() { return intMonth = (intYear/1200);}
bool setInterestMonth(double interest)
{
return true;
}
//Declare other member functions to be defined later...
void Amortization();
void Schedule();
void caseSchedule();
void enterLoanAmts();
}; // end class
// function to get input from the user...
double getRangedInput(const string prompt, double min, double max, int tries = 5);
void pause(); //pause
int menu = 0;
// Controls the main logic needed to interface with the user...
int main()
{
double loanAmount; // Initialize original amount of loan...
double term; // Initialize term of loan in years...
double numMonths;
double intMonth;
double paymentAmt;
char indicator;
MortgageCal morgCalc; // Redefine class as subclass...
do
{
system("cls");
cout << endl << "\"Welcome to our Mortgage Calculator!\"";
cout << "\n\n-------- Main Menu ---------";
cout << "\n 1. Would you like to enter rate and term ";
cout << "\n 2. Would you like to select loan from menu ";
cout << "\n----------------------------\n";
cout << "Press 1 or 2: ";
cin >>menu;
//Loop after selecting type of loan
if (menu == 1)
{
morgCalc.enterLoanAmts();
}
else if (menu == 2)
{
morgCalc.caseSchedule();
/*cout << "After Amortinzation:\n"
<< endl
<< "Your payments will be: $" << paymentAmt; //MortgageCal.getPaymentAmount();*/
//morgCalc.Amortization();
//morgCalc.Schedule();
}
cout<< "\nEnter another loan (y)es or (n)o):";
cin>>indicator;
} while(indicator=='y');
return 0;
} // end main
/**
*Function for getting input from the user.
* If the user enters an invalid string, or if the user enters a value outside of the
* given range then it will give the user an error message...
*/
double getRangedInput(const string prompt, double min, double max, int tries)
{
int userTry = 0;
double userInVal = 0;
bool isValidInput;
do {
cout << prompt << ": ";
cin >> userInVal;
if (!cin.good())
{
cout <<endl;
cout << "INPUT ERROR: Please input a proper number!" << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
isValidInput = false;
} else
{
isValidInput = (userInVal >= min && userInVal <= max);
}
if (!isValidInput)
{
cout << "Please enter a value between " << min << " and " << max << "!" << endl;
cout << endl;
}
} while (!isValidInput && ++userTry < tries); // end while...
if (userTry == tries)
{
cout << "User input invalid, can not process!" << endl;
exit(1); //If the user can't input a valid value, exit the program...
}
return userInVal;
} // end of get for error input...
void MortgageCal::Schedule()
{
int intPymtNum = 1; // counter for payments
int max = 0; // displays maximum lines on screen
double intRate; // calculated loan interest
double intPayment; // interest amount applied to loan
double principleAmt; // principle amount applied to loan
double loanBal; // running balance of loan
cout << endl
<< "This is a breakdown of "
<< "how much of your payment is applied " << endl;
cout << "to interest and the "
<< "balance of your loan: " << endl;
system ( "PAUSE" );
cout << endl << endl; // headings
cout << " Payment" << setw(15) << "Interest"
<< endl;
cout << " Number " << setw(15) << " Paid "
<< setw(14) << "balance " << endl;
cout << " _______" << setw(15) << "________"
<< setw(14) << "________" << endl;
loanBal = loanAmt; // used for running total
cout.setf(ios::fixed); // fixed not scientific format
cout.setf(ios::showpoint); // trailing 0's
cout.precision(2); // 2 places
for(int i = 1, max = 1; intPymtNum <= numMonths; i++)
{
// controls the loop of monthly payments
intRate = intMonth; //intMonth;
intPayment = loanBal * intRate;
principleAmt = paymentAmt - (loanBal * intRate);
loanBal = loanBal - principleAmt;
if (loanBal <= 0)
{
loanBal = 0; // to avoid negative numbers
}
cout << endl
<< setw(5) << intPymtNum << setw(17)
<< intPayment << setw(15) << loanBal;
intPymtNum++; // adds 1 to payment number
max++; // adds 1 to line count
if (max == 20) // loop pauses program every 19 lines
{
cout << endl;
system ( "PAUSE" );
max = 1; // resets line count
cout << endl << endl; // prints headings again
cout << " Payment" << setw(15) << "Interest"
<< endl;
cout << " Number " << setw(15) << " Paid "
<< setw(14) << "balance " << endl;
cout << " _______" << setw(15) << "________"
<< setw(14) << "________" << endl;
} // end if loop
} // end for loop
} // end MortgageCal::Schedule
void pause()
{
cout << "Press enter to continue...";
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cin.ignore();
}
/*define member functions...
Determines monthly interest in decimal format
Set up monthly payment calculations...*/
void MortgageCal::Amortization()
{
numMonths = term * 12; // Converts years to months...
intMonth = intYear/1200; // Converts annual rate to monthly rate...
paymentAmt = (loanAmt*intMonth)/(1-pow(1+intMonth,-numMonths)); // Amortization formula...
}
void MortgageCal::caseSchedule()
{
//Local Variables
int checklist = 0; //Check for if loop to make sure proper entry
int choice=0; //Verify choice of loan and send to array
int ary; //Choice of array from if loop
int iarray[3] = {0};
float farray[3] = {0.0F};
ifstream in("calculations");
in >> iarray[0] >> iarray[1] >> iarray[2];
in >> farray[0] >> farray[1] >> farray[2];
do
{
//Setup menu for loan to choose which term and interest rate
cout<<"\n------Loan Menu Items------";
cout<< "\n1) 7 years at 5.25% \n2) 15 years at 5.5% \n3) 30 years at 5.75%\n-------------------------\nEnter (1-3)";
cin >> choice;
checklist = 0; //Reset checklist to 0 on loop
if(choice <= 0) //Error if user chooses 0 on loop
{
cout<<"\n\n\n";
cout<<"\n\nError! Please enter only 1, 2, or 3 to select the term and rate\n";
checklist = 1;
}
else if(choice == 1) //Send to array
{
ary=0;
}
else if(choice == 2) //Send to array
{
ary=1;
}
else if (choice ==3) //Send to array
{
ary=2;
}
else if (choice > 3) //Error if user chooses a number greater then 3
{
cout<<"\n\n\n";
cout<<"\n\nError! Please enter only 1, 2, or 3 to select the term and rate\n";
checklist = 1;
}
cout<<"Please enter the Loan Amount:$";
cin >> loanAmt;
}
while (checklist == 1);
numMonths = (iarray[ary] * 12); //Set Term for Mortgage Calculation
intMonth = (farray[ary]/1200); //Set Interest for Mortgage Calculation
paymentAmt = (loanAmt*intMonth)/(1-pow(1+intMonth,-numMonths)); // Amortization formula...
cout << "After Amortinzation:\n"
<< endl
<< "Your payments will be: $" << paymentAmt; //MortgageCal.getPaymentAmount();
MortgageCal::Schedule();
} // End MortgageCal::caseSchedule
void MortgageCal::enterLoanAmts()
{
double loanAmount;
double yearlyRate;
MortgageCal morgCalc;
char indicator = ('y', 'Y'); // set indicator to 'y' for continue...
while ((indicator =='y') || (indicator == 'Y')) // to continue loop as long as input = y
{
/*get and set all of the input from the user/ranges...
Set up screen output to display mortgage amount, interest
rate and term of loan...*/
loanAmount = getRangedInput("Please enter the loan amount", 0, numeric_limits<double>::max());
cout << endl;
term = getRangedInput("Please enter the loan term in years", 0, 10000);
cout << endl;
yearlyRate = getRangedInput("Please enter the yearly interest rate", 0, 100);
cout << endl;
morgCalc.setLoanAmount(loanAmount);
morgCalc.setTermInYears(term);
morgCalc.setYearlyRate(yearlyRate);
//display the payment calculations...
morgCalc.Amortization();
cout << "After Amortinzation:\n"
<< endl
<< "Your payments will be: $" << morgCalc.getPaymentAmount();
morgCalc.Schedule();
cout << endl;
pause(); // to get user input to enter new values...
cout << endl; // Enter newline...
//Set up screen for input on whether to enter new numbers or exit...
cout << "Do you want to enter another value (enter y to continue or n to end)? ";
cin >> indicator; // Read indicator input...
} //end while
cout << endl;
cout << "\"Thank you for using our mortgage calculator\"" << endl;
cout << endl;
//cout<< "\nEnter another loan (y)es or (n)o):";
//cin>>indicator;
pause();
} // End MortgageCal::enterLoanAmts()
I had the code that I selected from a switch statement to get the variables and that worked fine too. The code may not have been the best but it worked. But this time I have to read from a sequential file for the variables to get my data.
Please help and Thanks,
Ken