c++While循环打印couts两次

c++ While loops prints the couts twice

本文关键字:两次 couts 打印 循环 c++While      更新时间:2023-10-16

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

你想做什么?

存款

提取

取消

但是,它显示了两次。

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"。

您同时使用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中的文本行。这是悲伤和虫子的配方。

除了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);
}