c++ - C++ 中的循环不再工作

标签 c++ loops double

所以我一直在对这个程序进行故障排除,并且我之前已经问过有关它的问题。我认真听取了别人的建议并将其应用到我的程序中,但仍然不起作用。这是修改后的(尽管缩短了)代码:

#include <iostream>
#include <string>

double balance, withdraw, deposit;
std::string choice;

void withdrawmon()
{
    balance -= withdraw;
}
void depositmon()
{
    balance += deposit;
}

int main()
{
    std::cout << "Welcome to the Bank Program." << std::endl;
    std::cout << "Enter a starting balance: ";
    std::cin >> balance;
    std::cin.clear();
    do
    {
        std::cout << "Withdraw, deposit, or quit: ";
        std::getline (std::cin, choice);
        if(choice == "withdraw")
        {
            std::cout << "Enter amount to withdraw: ";
            std::cin >> withdraw;
            withdrawmon();
            std::cout << "Your current balance is $" << balance << std::endl;
        }
        else if(choice == "deposit")
        {
            std::cout << "Enter amount to deposit: ";
            std::cin >> deposit;
            depositmon();
            std::cout << "Your current balance is $" << balance << std::endl;
        }
    }
    while(choice != "quit");
    std::cout << "Thanks for using the Bank Program. Your final balance was $" << balance << std::endl;
    return 0;
}

不会有问题,代码会运行,但输出是这样的: https://www.dropbox.com/s/aocn6asjr4ofcws/Broken%20Output.PNG

正如您所看到的,每当循环重新启动时,“取款、存款或退出:”行就会自行打印两次。有人知道为什么吗?任何帮助表示赞赏。就 C++ 而言,我是一名新程序员,因此非常感谢您的帮助。

最佳答案

cin.clear() 清除错误标志,并将输入余额后面的行的剩余内容保留在缓冲区中。您需要调用cin.ignore()来正确处理这个问题。

cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

关于c++ - C++ 中的循环不再工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18008672/

相关文章:

java - 找到随机数组的最大值

c - 除法结果始终为零

mysql - 在 MySQL 中存储 CLLocationDegrees 时精度丢失

html - Jekyll 每 4 个循环中的项目显示不同

C++ 默认构造函数与具有非平凡默认构造函数的变体成员 union

c++ - glm::dot 返回一个 vector

c++ - 如何在一行中检查 std::vector 中是否存在元素?

python - 在带有列表的python中嵌套for循环

c - 如何获取 *chars 并返回非整数?

c++ - mov bl 在汇编中做了什么