Deadalus
Deadalus

Reputation: 1

fflush(stdin) not working and letting a loop continue

Here's the code

#include <iostream>
#include <iomanip>

void showBalance(double balance);
double deposit();
double withdraw(double balance);

int main()
{
    int choice = 0;
    double bal = 0;

    std::cout << "************ Banking ************\n";

    do
    {

        std::cout << "Welcome to your bank acount! Choose one of the following\n";
        std::cout << "1. Deposit\n";
        std::cout << "2. Withdraw\n";
        std::cout << "3. Show balance\n";
        std::cout << "4. Exit\n";

        std::cin >> choice;

        std::cin.clear();
        fflush(stdin);

        switch(choice)
        {
            case 1: bal += deposit();
                    showBalance(bal);
                    break;
            case 2: bal -= withdraw(bal);
                    showBalance(bal);
                    break;
            case 3: showBalance(bal);
                    break;
            case 4: std::cout << "Thanks for visiting!\n";
                    std::cout << "*******************************\n";
                    break;
            default: std::cout << "Invalid output";

        }
    } while (choice != 4);
    
        


    return 0;
}

void showBalance(double balance)
{
    std::cout << "You have $" << std::setprecision(2) << std::fixed << balance << " in your account\n";
}

double deposit()
{
    double deposit;

    std::cout << "How much would you like to deposit?: ";
    std::cin >> deposit;

    if(deposit > 0)
    {
        return deposit;
    }else{
        std::cout << "That's not a valid amount\n";
        return 0;
    }

    
}

double withdraw(double balance)
{
    double withdraw;

    std::cout << "How much would you like to withdraw?: ";
    std::cin >> withdraw;

    if(withdraw > balance)
    {
        std::cout << "Insufficient Balance! \n";
    }

    return withdraw;
}

I was following a practice for a bank program and it showed that I can use fflush(stdin) to avoid an infinite loop but when I tried it just kept repeating

I tried to reload and move to a different file and the problem persisted and then I retyped it only to continue having the same issue

Upvotes: 0

Views: 32

Answers (0)

Related Questions