C++使用 dowhile 进行验证

C++ validation using dowhile

本文关键字:验证 dowhile 使用 C++      更新时间:2023-10-16
这是我

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

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 在循环之外,因此它只出现一次。

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