gpt4 book ai didi

使用 dowhile 的 C++ 验证

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:46:53 24 4
gpt4 key购买 nike

这是我的代码,但如果用户输入要检查的值之一,它会发现错误,但会在无限循环中显示错误消息

std::cin >> withdrawAmount;
do
{
if (withdrawAmount < balance && withdrawAmount > 0)
{
break;
}
std::cout << "Error: You have insufficient balance to withdraw " << withdrawAmount << " pounds. Your balance is only " << balance << " pounds." << std::endl;
std::cout << "Or you have entered a non positive integer" << std::endl;
}
while (true);

// some more code

而这段正确工作的代码对我来说看起来是一样的

std::cout << "Please enter todays date: (as an integer) ";
do
{
std::cin >> date;
if (date > 1 && date < 31)
{
break;
}
std::cout << "Error: Please enter todays date: (as an integer) ";
}
while (true);

// some more code

此外,如果有人可以告诉我如何添加验证以检查他们输入的内容实际上是一个整数(例如不是“二”,那就太棒了)

最佳答案

对于你的主要问题,cin 在循环之外,所以它只出现一次。

对于您的第二个问题,请调用 fail()提取后 std::cin 的成员函数。

关于使用 dowhile 的 C++ 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20951323/

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