使用do while进行C ++验证

时间:2014-01-06 13:44:39

标签: c++ validation loops do-while

这是我的代码,但如果用户输入其中一个要检查的值,则会收到错误,但会在无限循环中显示错误消息

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

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

1 个答案:

答案 0 :(得分:2)

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

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