How can I get user input to exit a loop? - c++

I have a problem with my code, every time I loop it with the answer 'y'(Yes) it loops to infinity?
I'm trying to make a loan calculator and every time the user is done calculating with a transaction and wants to reset, and do another calculation if he enters in a value 'y', and if he enters 'n' the program will end.
Here's my code so far:
#include <iostream>
#include <string>
#include <iomanip>
#include <cmath>
using namespace std;
int main() {
char ans = 'y';
do {
string name;
int Months;
int n;
double LoanAmount, Rate, MonthlyInterest, TotalLoanAmount, MonthlyAmortization, OutstandingBalance;
cout << fixed << showpoint;
cout << "Enter Name of Borrower: ";
getline(cin, name);
cout << "Enter Loan Amount: ";
cin >> LoanAmount;
cout << "Enter Number of Months to Pay: ";
cin >> Months;
cout << "Enter Interest Rate in Percent(%): ";
cin >> Rate;
cout << setprecision(2);
MonthlyInterest = LoanAmount * Rate;
TotalLoanAmount = LoanAmount + (MonthlyInterest * Months);
cout << "Monthly Interest: " << MonthlyInterest << endl
<< "Total Loan Amount with interest: " << TotalLoanAmount << endl;
cout << setw(100)
<< "\n\tSUMMARY OF OUTSTANDING INSTALLMENT" << endl
<< "\tName of Borrower: " << name
<< "\n\nMonth\t\tMonthly Amortization\t\tOutstanding Balance"
<< "\n";
for(n = 1; n <= Months; n++) {
MonthlyAmortization = TotalLoanAmount / Months;
OutstandingBalance = TotalLoanAmount - MonthlyAmortization;
cout << n << "\t\t" << MonthlyAmortization << "\t\t\t" << n - 1 << OutstandingBalance << endl;
}
cout << "\nEnd of Transaction";
cout << "Do you want to compute another transaction?[y/n]?" << endl;
cin >> ans;
}
while(ans == 'y');
}

After your cin>>ans, add these two lines :
cin.clear();
cin.sync();
That usually fixes a lot of the infinite looping problems I get with cin.
Also, I would recommend against initializing ans as 'y' when you declare it. I don't think this is causing you problems but it's an uncessesary thing.

You seem to expect pressing y and enter to register as only 'y'. If you want to get the input of just one character have a look at std::cin.get(char)

Related

Program cannot run due to no operator "<<" matches these operands

I get an error of "no operator matches these operands" when using the part of the code outputFile << customerName << "your Monthly payments are " << monthlyPay << endl;. Overall, I need the code to Add the ability to save data to disk in one or more files and a menu should give the user the option to save or retrieve data. I have not gotten past the error to properly run the program. Can you please help fix error.
#include <iostream>
#include <string>
#include <cmath>
#include <iomanip>
#include <vector>
#include<fstream>
using namespace std;
void menu(void);
void writeData(void);
void readData(void);
const char FileName[] = "CourseProjectAvilaF.txt";
//Variables
vector <double> Loanlgth, Loanamt, interestRate, totalInterest;
vector <double> monthlyPay(100), loanTotal(100), creditScore(100);
vector <string> customerName;
int main()
{
menu();
return 0;
}
void menu(void)
{
const int INPUT_CUSTOMER = 1, DISPLAY_LOAN = 2, EXIT_PROGRAM = 3;
int option;
//Program
cout << "Thank you for choosing The Bank of UA for your loan requirements!\n\n";
do
{
cout << "UA Bank menu:\n\n"
<< "1. Enter your information\n"
<< "2. See your loan requirements\n"
<< "3. Exit program\n\n"
<< "Choose an option: ";
cin >> option;
while (option < INPUT_CUSTOMER || option > EXIT_PROGRAM)
{
cout << "Please enter a valid menu option: ";
cin >> option;
}
if (option == 1)
{
writeData();
}
if (option == 2)
{
readData();
}
} while (option != EXIT_PROGRAM);
}
//function to read customer information
void writeData(void)
{
fstream outputFile;
outputFile.open(FileName, fstream::app);
int index;
int numCustomers = 0;
cout << "Please enter the number of customers you would like\n"
<< " to enter loan information for: ";
cin >> numCustomers;
for (index = 0; index < numCustomers; index++)
{
string tempName;
double tempLoanamt, tempLoanlgth, tempcreditScore, tempinterestRate,
tempinterest;
cout << "Please enter your name: ";
cin >> tempName;
customerName.push_back(tempName);
cout << "Please enter the loan amount: $";
cin >> tempLoanamt;
Loanamt.push_back(tempLoanamt);
cout << "Please enter the length of the loan in months: ";
cin >> tempLoanlgth;
Loanlgth.push_back(tempLoanlgth);
cout << "What is your current credit score? ";
cin >> tempcreditScore;
creditScore.push_back(tempcreditScore);
//This will determine interest rate and overall loan amount when calculated
if (tempcreditScore <= 650)
tempinterestRate = .12;
else
tempinterestRate = .05;
interestRate.push_back(tempinterestRate);
//Calculations
tempinterest = Loanamt[index] * interestRate[index];
totalInterest.push_back(tempinterest);
loanTotal[index] = (Loanamt[index] + totalInterest[index]);
monthlyPay[index] = loanTotal[index] / Loanlgth[index];
// Out put files to write data to be saved
outputFile << customerName << "your Monthly payments are " << monthlyPay << endl;
outputFile << "Your total interest is " << totalInterest << endl;
outputFile << "You owe " << loanTotal << endl;
outputFile << "You have " << Loanlgth << " months to pay off your balance" << endl;
}
outputFile.close(); //Close file
}
//function loan information
void readData(void)
{
int index;
int numCustomers = 0;
ifstream inputFile;
inputFile.open(FileName, fstream::in);//Open the file with read mode
//Display monthly payment
cout << fixed << setprecision(2);
for (index = 0; index < numCustomers; index++)
{
cout << customerName[index] << " your total loan is " << loanTotal[index]
<< "\n"
<< "with a monthly payment of $" << monthlyPay[index] << "\n"
<< "for " << Loanlgth[index] << " months with an interest\n"
<< "rate of " << interestRate[index] << endl;
}
}
It's simple enough, you got it right everywhere else in your program.
When you want to access a particular element of a vector you use an index. Like this
outputFile << customerName[index] << "your Monthly payments are " << monthlyPay[index] << endl;
outputFile << "Your total interest is " << totalInterest[index] << endl;
outputFile << "You owe " << loanTotal[index] << endl;
outputFile << "You have " << Loanlgth[index] << " months to pay off your balance" << endl;
customerName and monthlyPay are vectors. You can't stream them directly. Instead you can do something like
for (auto const &name : customerName)
outputFile << name;

C++: interestEarned coming back wrong

I'm learning C++ and this is an assignment I have to do, it's complete but my interestEarned is not coming back correctly but the bankBalance is correct so I'm just not displaying interestEarned correctly. "Total Interest Earned: $65.50" is incorrect is supposed to display "$120.50" as my teacher said. What am I doing wrong?
Here is my code:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
// Variables
int numOfCustomers, numOfMonths = 0;
double bankBalance, depositAmount, withdrawnAmount, interestRate, interestEarned = 0.0;
const int MIN = 0;
// Asking for Number of Customers
cout << "Enter the number of customers: ";
cin >> numOfCustomers;
// Making sure the input was not 0 or lower
while (numOfCustomers <= MIN) {
cout << "==>Number of customers must be at least 1. Try again: ";
cin >> numOfCustomers;
}
// Validating each Customer
for (int c = 1; c < (numOfCustomers + 1); c++) {
// Start of each Customer
cout << "\nCUSTOMER " << c << ":\n";
// Asking for Number of Months --
cout << "Enter the number of months the account has been opened: ";
cin >> numOfMonths;
// Making sure the input was not 0 or lower
while (numOfMonths <= MIN) {
cout << "==>Number of months must be at least 1. Try again: ";
cin >> numOfMonths;
}
// Asking for Starting Balance --
cout << "Enter the starting balance: $";
cin >> bankBalance;
// Making sure the input was not 0 or lower
while (bankBalance < MIN) {
cout << "==>Starting balance can't be negative. Try again: $";
cin >> bankBalance;
}
// Asking for Monthly Interest Rate --
cout << "Enter the monthly interest rate as a decimal (i.e. 0.05 = 5%): ";
cin >> interestRate;
// Making sure the input was not 0 or lower
while (interestRate < MIN) {
cout << "==>Monthly interest rate can't be a nagative. Try again: ";
cin >> interestRate;
}
// Validating each Month
for (int m = 1; m < (numOfMonths + 1); m++) {
// Deposit Amount
cout << "\nEnter deposit amount for Month " << m << ": $";
cin >> depositAmount;
bankBalance = bankBalance + depositAmount;
// Withdrawn Amount
cout << "Enter withdrawn amount for Month " << m << ": $";
cin >> withdrawnAmount;
bankBalance = bankBalance - withdrawnAmount;
// Calculating Interest Earned
interestEarned = bankBalance * interestRate;
// Complete bankBalance
bankBalance = bankBalance + interestEarned;
}
// Account Summary
cout << "\nACCOUNT SUMMARY" << endl;
cout << fixed << setprecision(2);
cout << "Number Months Active: " << numOfMonths << endl;
cout << "Ending Balance: $" << bankBalance << endl;
cout << "Total Interest Earned: $" << interestEarned << endl;
}
system("pause");
return 0;
}
Use another variable that is initialized to zero before the loop. In the loop, add the value of interestEarned to it. - #Peter

how do you do a integer validation in C++?

ok, I have been looking for days now but I cant find anything that will work.
I have a program and I want to make sure that the user enters a integer and not a double.
this program works fine but I need to validate the numOne and numTwo to make sure they are integers and not doubles, (5.5)
int main()
{ //This is where my variables are stored
int numOne, numTwo, answer, rightAnswer, ranNumOne, ranNumTwo;
//this will display to the user to enter a range of numbers to be used
cout << "Please enter a set of numbers to be the range for the problems." << endl;
cout << "Please enter the beginning number." << endl;
cin >> numOne;
cout << "please enter the ending number." << endl;
cin >> numTwo;
//this makes sure that the user entered a integer(if not the program will close)
if (!(cin >> numOne))
{
cout << "You did not enter a integer PLEASE RE-RUN THE PROGRAM AND TRY AGAIN!" << endl;
cin.clear();
cin.ignore(100, '\n');
exit(0);
}
cout << "please enter the ending number." << endl;
cin >> numTwo;
//this makes sure that the user entered a number(if not the program will close)
if (!(cin >> numTwo))
{
cout << "You did not enter a integer PLEASE RE-RUN THE PROGRAM AND TRY AGAIN!" << endl;
cin.clear();
cin.ignore(100, '\n');
exit(0);
}
//this is where the first number is generated
srand(time(0));
ranNumOne = rand() % (numOne - numTwo) + 1;
system("PAUSE");
//this is where the second number is generated
srand(time(0));
ranNumTwo = rand() % (numOne - numTwo) + 1;
//this is where the calculations are done
rightAnswer = ranNumOne + ranNumTwo;
//this displays the problem that was generated
cout << "What is: " << endl;
cout << setw(11) << ranNumOne << endl;
cout << setw(6) << "+" << setw(3) << ranNumTwo << endl;
cout << " -------\n";
cin >> answer;
//this checks to see if the answer is right or not and displays the result
if (answer == rightAnswer)
{
cout << "Your answer was correct! " << endl;
}
else
cout << "The correct answer is: " << rightAnswer << endl;
return 0;
}
Use std:n:ci.fail() to see if it failed.
int numOne;
cin >> numOne;
if(cin.fail())
cout << "Not a number...")
Maybe even a nice template function.
template<typename T>
T inline input(const std::string &errmsg = "") {
T var;
std::cin >> var;
while (std::cin.fail()) {
std::cin.clear();
std::cin.ignore(256, '\n');
std::cout << errmsg;
std::cin >> var;
}
return var;
}
Or not:
#include <iostream>
#include <cstdlib>
#include <iomanip>
#include <string>
#include <ctime>
#define DIFF(n1, n2) (n1 > n2 ? n1 - n2 : n2 - n1)
using namespace std;
int input(const string &firstmsg = "", const string &errmsg = "") {
int var;
std::cout << firstmsg;
std::cin >> var;
while (cin.fail()) {
cin.clear();
cin.ignore(256, '\n');
cout << errmsg;
cin >> var;
}
return var;
}
int main(){
//This is where my variables are stored
int numOne, numTwo, answer, rightAnswer, ranNumOne, ranNumTwo;
//this will display to the user to enter a range of numbers to be used
cout << "Please enter a set of numbers to be the range for the problems." << endl << endl;
numOne = input("Please enter the beginning number: ", "Invalid. Enter again: ");
//this asks the user for the second number
numTwo = input("Please enter the ending number: ", "Invalid. Enter again: ");
//this is where the first number is generated
srand(time(0));
ranNumOne = rand() % (DIFF(numOne, numTwo)) + 1; // ensures it will always be positive
system("PAUSE");
//this is where the second number is generated
srand(time(0));
ranNumTwo = rand() % (DIFF(numOne, numTwo)) + 1;
//this is where the calculations are done
rightAnswer = ranNumOne + ranNumTwo;
//this displays the problem that was generated
cout << "What is: " << endl;
cout << setw(11) << ranNumOne << endl;
cout << setw(6) << "+" << setw(3) << ranNumTwo << endl;
cout << " -------\n";
cin >> answer;
//this checks to see if the answer is right or not and displays the result
if (answer == rightAnswer){
cout << "Your answer was correct! " << endl;
}
else
cout << "The correct answer is: " << rightAnswer << endl;
return 0;
}
why not, get the number into a double and then see if that double is an int. ie
double d;
cin>>d;
if (ceil(d) != d)
cout >> " not an integer";

How do I incorporate input validation in this code?

I am trying to implement input validation into this program but it keeps coming out wrong. I tried using another while statement but it didn't work. It normally pops up with the text which shouldn't be. I want it to show after the person inputs the wrong information. I want it so that if the data entered is invalid, they will have to re enter it.
Here is the code I have so far.
/*
1. Declare variables for month 1, 2, and 3.
2. Declare variable for Total and Average Rainfall
3. Ask user to input name of months.
4. Then ask user to input inches of rain fall.
5. Add all inches and then divide by number of inches asked. In this case, 3.
6. Display average inches of rain for all months to user.
*/
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
string month1, month2, month3;//Declared values for months aswell as total and average rainfall.
double month1Inch, month2Inch, month3Inch;
double averageInches;
double totalInches;
char c = 'y';
do
{
cout << setprecision(2) << fixed;
cout << "Enter first month's name:";
cin >> month1;
cout << "Enter rain inches for " << month1 << ":";
cin >> month1Inch;
cout << "\n";
cout << "Enter second month's name:";
cin >> month2;
cout << "Enter rain inches for " << month2 << ":";
cin >> month2Inch;
cout << "\n";
cout << "Enter third month's name:";
cin >> month3;
cout << "Enter rain inches for " << month3 << ":";
cin >> month3Inch;
cout << "\n";
totalInches = (month1Inch + month2Inch + month3Inch);
averageInches = (totalInches) / 3;//calculating the average
//Display calculated data.
cout << "The average rainfall for " << month1 << ", " << month2 << ", " << "and " << month3 << " is " << averageInches << endl;
cout << "Would you like to recalculate? Either enter Y to run or N to not." << endl;
cin >> c;
} while (c == 'Y'||c=='y');
if (c != 'Y' || c != 'y')
cout << "you must enter the correct choice" << endl;
system("pause");
return 0;
}
I tried putting an if statement under "cout << "Would you like to recalculate? Either enter Y to run or N to not." << endl;
cin >> c;" but i get an infinite loops.
I am not getting any error codes. Just the text showing up with "would you like to recalculate?" line and infinite loops.
Even when I input the data with that showing, I get an infinite loop somewhere. So I deleted it.
It sounds like you want to validate the Yes or No response. That requires a loop that exits only when you have an acceptable input. It's separate from the loop that decides if the calculation should be run again.
int main() {
// ...
do {
// ...
do {
cout << "Would you like to recalculate? Either enter Y to run or N to not." << endl;
cin >> c;
} while (c != 'Y' && c != 'y' && c != 'N' && c != 'n');
} while (c == 'Y'|| c=='y');
system("pause");
return 0;
}

KSP DELTA V FINDER: Why does C++ assume that log( ) is a function?

I'm attempting to create a program to figure out Delta-V for my Kerbal Space Program game, and C++ (being run in the Eclipse IDE) does not allow for use of log() without assuming I'm trying to call a function. Thank you so much for help! It's really nice of you.`
#include <iostream>
#include <cmath>
using namespace std;
int main() {
cout << "Hello. Welcome to the Kerbal Space Program Delta V Calculator. \n";
cout << " \n";
cout << "Note that each stage must use the same engine for this calculator.";
cout << "\n";
cout << "\nHow many stages make up your rocket? :";
int stageNumber;
cin >> stageNumber;
//cout << "Your rocket has " << stageNumber << " stages.\n";
cout << "\n\nStart from the bottom stage, please. ";
//ACTUAL DELTA V CALCULATIONS
for(int currentStage = 1; currentStage <= stageNumber; currentStage = currentStage + 1){
cout << "What is the total mass of this stage? :";
int totalMass;
cin >> totalMass;
cout << "What is the fuel mass of this stage? :";
int fuelMass;
cin >> fuelMass;
cout << "\n";
int dryMass;
dryMass = totalMass - fuelMass;
cout << "Your dry mass is" << dryMass << "\n";
cout << "\n";
cout << "Give the specific impulse of this stage's engine. \n";
int iSP;
cin >> iSP;
cout << "Here is the Delta V of your rocket.\n";
int deltaMass;
deltaMass = totalMass/dryMass;
int deltaV;
deltaV = iSP * log(deltaMass);
cout << deltaMass
exit(0);
}
}
`
log() is a function in the C standard library that takes the natural logarithm of a number. The name is effectively reserved — pick something else.