2

所以我写了这段代码:

#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;
}

当我尝试运行代码时,我得到以下输出: --> 欢迎来到银行计划!您想提款、存款还是退出程序:存款请输入存款金额:100新余额为:100 美元您想再试一次还是退出:再试一次您想提款,a存款或退出程序:输入无效。你想再试一次还是退出:<-- 它将继续这样做,直到我退出程序。有谁知道为什么?粗体字是我的输入,斜体是计算机自己输入的。箭头中的所有内容都是控制台文本。

4

2 回答 2

4

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

因为您输入try again了 ,读入的值quitOrNo将是try,将文本留again在流中。当你循环并读入时choice,你会得到again无效的。因为你不断地输入同样的东西,你不断地遇到同样的问题。

您应该考虑std::getline改用。

于 2013-08-02T01:43:55.580 回答
4

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

我不确定它是否或如何进入无限循环,但如果cin无法处理已给出的某些输入,它将停止接受更多输入,直到您调用cin.clear(). 与此同时,一个语句if (cin)将看到cin评估为false。默认情况下,缺少这种检查的程序通常会读取无限的无效输入。

于 2013-08-02T01:41:09.810 回答