Search code examples
c++loopsinfinite-loopnested-loops

How can I get user input to exit a loop?


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');


}

Solution

  • 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.