簡體   English   中英

c ++ While 循環將 couts 打印兩次

[英]c++ While loops prints the couts twice

在我的代碼中,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::cin operator>>不消耗尾隨的換行符,因此對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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM