c ++ While循环打印两次couts

时间:2016-04-19 23:13:50

标签: c++ while-loop

在我的代码中,while循环打印cout两次,它应该打印一次,以及函数的couts。我不明白为什么要这样做 - 它应该显示

  

你想做什么?

     

存款

     

退出

     

取消

但是,它会显示两次。

while (yesNo == 'Y') {

        cout << "What would you like to do?"
            << endl
            << endl;

        menu();
        getline(cin, bankChoice);

        if (bankChoice == "Withdraw")
        {

            withdrawTotal = withdraw(bankAmount);
            bankAmount = withdrawTotal;
            cout << "You now have $"
                << bankAmount
                << " in your account."
                << endl;

            cout << "Would you like to do anything else?"
                << endl
                << "Y/N: ";
            cin >> yesNo;

        }

        if (bankChoice == "Deposit")
        {

            depositTotal = deposit(bankAmount);
            bankAmount = depositTotal;
            cout << "You now have $"
                << bankAmount
                << " in your account."
                << endl;

            cout << "Would you like to do anything else?"
                << endl
                << "Y/N: ";
            cin >> yesNo;
        }


        if (bankChoice == "Cancel") {
            return 0;
        }

    }

这就是我正在使用的循环。如果需要额外的代码,我也可以发布它,但这是造成问题的部分。我已经尝试了没有它的代码并且工作正常,但是我想让代码循环直到用户输入N&#39;。

2 个答案:

答案 0 :(得分:2)

您正在使用std::getlineoperator>>来阅读std::cinoperator>>不使用尾随换行符,因此下一次调用std::getline()将立即读取以下换行符并将其解释为输入的空行文本。这将贯穿循环,并返回到顶部,以进行第二次提示。

当您打算阅读一行文字时,切勿将operator>>std::cin一起使用。

以下简短示例说明了这一点:

#include <iostream>
#include <string>

int main()
{
    char c;
    std::string l;

    std::cin >> c;

    std::cout << "A line of text please: ";

    std::getline(std::cin, l);
}

运行它,输入“Y”,并尝试自己解决,为什么程序会立即终止。

再次:不要使用operator>>来阅读std::cin中的文字行。这是悲伤和错误的秘诀。

答案 1 :(得分:0)

除了Sam的回答之外,我还建议您在两个if语句之外提取常用功能:

std::string yesNo;

while (yesNo.compare("Y") == 0) {
    cout << "What would you like to do?"
        << endl
        << endl;

    menu();
    getline(cin, bankChoice);

    if (bankChoice == "Cancel")
        return 0;

    if (bankChoice == "Withdraw") {
        withdrawTotal = withdraw(bankAmount);
        bankAmount = withdrawTotal;
    }

    if (bankChoice == "Deposit") {
        depositTotal = deposit(bankAmount);
        bankAmount = depositTotal;
    }

    cout << "You now have $"
        << bankAmount
        << " in your account."
        << endl;

    cout << "Would you like to do anything else?"
        << endl
        << "Y/N: ";

    std::getline(std::cin, yesNo);
}