在C ++中循环不正确

时间:2013-08-02 01:35:41

标签: c++ loops

所以我写了这段代码:

#include <iostream>
#include <string>
using namespace std;

double balance = 0, withdraw = 0, deposit = 0;
string choice, quitOrNo;

class Bank
{
    public:
        void withdrawMoney()
        {
            if(balance - withdraw >= 0)
            {
                balance = balance - withdraw;
            }
            else
            {
                cout << "$5 penalty for attempting to withdraw more than you have.";
                balance -= 5;
            }
        }
    public:
        void depositMoney()
        {
            balance = balance + deposit;
        }
};
int main()
{
    Bank bankObject;
    cout << "Welcome to the Bank Program!" << endl;
    while(true)
    {
        while(true)
        {
            cout << "Would you like to make a withdrawal, a deposit, or quit the program: ";
            cin >> choice;
            if(choice.compare("withdrawal") == 0 || choice.compare("w") == 0)
            {
                cout << "Please enter the amount to withdraw: ";
                cin >> withdraw;
                bankObject.withdrawMoney();
                cout << "New balance is: $" << balance << endl;
                break;
            }
            else if(choice.compare("deposit") == 0 || choice.compare("d") == 0)
            {
                cout << "Please enter the amount to deposit: ";
                cin >> deposit;
                bankObject.depositMoney();
                cout << "New balance is: $" << balance << endl;
                break;
            }
            else if(choice.compare("quit") == 0 || choice.compare("q") == 0)
            {
                break;
            }
            else
            {
                cout << "Invalid input." << endl;
                break;
            }
        }
        if(choice.compare("quit") == 0)
        {
            break;
        }
        cout << "Would you like to try again or quit: ";
        cin >> quitOrNo;
        if(quitOrNo.compare("quit") == 0)
        {
            break;
        }
    }
    cout << "Thank you for using the Bank Program." << endl;
    return 0;
}

当我尝试运行代码时,我得到了这个输出: - &GT;欢迎来到银行计划!您想要提款,存款或退出该计划:存款请输入存款金额: 100 新余额:100美元您想再试一次吗?或退出:再试一次您是要提款,退款还是退出该计划:输入无效。您想再试一次还是退出:&lt; - - 它将继续执行此操作,直到我退出程序。谁知道为什么? 粗体文本是我的输入,斜体文本是计算机给出的输入。箭头中的所有内容都是控制台文本。

2 个答案:

答案 0 :(得分:4)

try again是两个单词,但>>应用于std::string只提取一个单词。 again由下一个循环迭代提取。使用getline提取一行输入。

我不确定它是否或如何进入无限循环,但如果cin无法处理某些输入,那么它将停止接受任何更多输入,直到您调用cin.clear() 。在此期间,语句if (cin)cin评估为false。缺少此类检查的程序通常会默认读取无限的无效输入。

答案 1 :(得分:4)

问题是你正在读一个字符串,而不是整行。字符串输入由空格分隔,而不是以行尾为界。

由于您输入了try again,因此读入quitOrNo的值为try,文本again保留在流中。当您循环并阅读choice时,您将获得无效的again。因为你一直在输入相同的东西,所以你会遇到同样的问题。

您应该考虑使用std::getline代替。