gpt4 book ai didi

c++ - 在 C++ 中循环不正确

转载 作者:太空狗 更新时间:2023-10-29 23:51:58 25 4
gpt4 key购买 nike

所以我写了这段代码:

#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 您想再试一次吗或退出:再试一次 您要取款、存款还是退出程序:输入无效。您要再试一次还是退出:<--它将继续这样做,直到我退出程序。有人知道为什么吗? 粗体 文本是我的输入,斜体 文本是计算机给自己的输入。箭头中的所有内容都是控制台文本。

最佳答案

try again 是两个词,但应用于 std::string>> 仅提取一个词。 again 由下一个循环迭代提取。使用 getline 精确提取一行输入。

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com