C++输入验证(时间)

C++ Input Validation (Time)

本文关键字:时间 验证 输入 C++      更新时间:2023-10-16

你好,我正在尝试为时间做一个输入验证if语句。用户将输入一个数字,如果它是一个涉及时间的无效数字(即负数或25小时),代码将显示"无效输入",并将您返回到上一个问题,以便您可以重新输入有效输入。这是我目前所掌握的,但似乎不起作用。

cout << "Please enter the current processing hour." << endl;
    cin >> hr;          
    if (hr >= 0 && hr < 24)
        cout << "Invalid Input, try again.";
    cout << endl;
    cout << "Please enter the current processing minute." << endl;
    cin >> min;
    if (min >= 0 && min < 60)
        cout << "Invalid Input, try again.";
    cout << endl;
    cout << "Please enter the current processing second." << endl;
    cin >> sec;
    if (sec >= 0 && sec < 60)
        cout << "Invalid Input, try again.";
    cout << endl;

您的情况很糟糕:

我给你一个:

如果(hr>=0&&hr<24)

应该是

如果(hr<0||hr>23)

这是假设小时数可以从0到23。(正如Mike在下面建议的那样)

您需要一个循环,以便它可以返回并重试:

while(1) {
    cout << "Please enter the current processing hour." << endl;
    cin >> hr;          
    if (hr >= 0 && hr < 24)
        break;
    cout << "Invalid Input, try again.";
}
cout << endl;

您的代码没有循环。你的语句只是执行然后停止。您需要某种形式的循环,直到输入正确为止。

此外,您的if语句也没有花括号。因此,如果条件为true,它总是只执行下一个语句,如果条件是false,则跳过该语句。如果将括号放在那里,通常会更容易维护代码。

这里有一个示例片段来说明什么可以为您工作

using std::cout;
using std::cin;
using std::endl;
int hr;
int isValid = 0;
while(0 == isValid)
{
    cout << "Please enter the current processing hour." << endl;
    cin.clear();
    cin >> hr;
    cout << "Input '"<< hr << "'" << endl;
    if (hr >= 0 && hr < 24)
    {
        isValid = 1;
        cout << "Valid." << endl;
    }
    else
    {
        cout << "Invalid, try again." << endl;
    }
}

请注意,我是如何使用变量来跟踪输入状态,而不是通过break;逃离循环的。这使得函数只能有一种退出方式。通常这是降低错误率的一件好事。

下面是更详细的代码:

#include <iostream>
int getAndValidateInteger(const char * question, int min, int max);
int main(int argc, char* argv[])
{
    int hour, minutes, seconds;
    hour = getAndValidateInteger("Please enter the current processing hour.", 0, 23);
    minutes = getAndValidateInteger("Please enter the current processing minute.", 0, 59);
    seconds = getAndValidateInteger("Please enter the current processing second.", 0, 59);
    return 0;
}
int getAndValidateInteger(const char * question, int min, int max)
{
    using std::cout;
    using std::cin;
    using std::endl;
    int number;
    int isValid = 0;
    while(0 == isValid)
    {
        cout << question << " (Range [" << min << ";" << max << "])" << endl;
        cin.clear();
        cin >> number;
        cout << "Input '"<< number << "' " ;
        if (number >= min && number <= max)
        {
            isValid = 1;
            cout << "is valid." << endl;
        }
        else
        {
            cout << "is invalid, try again." << endl;
        }
    }
    return number;
}