简体   繁体   中英

How can I create a validate function that would validate the input from the user based on the specific input and its defined regular expression?

I am validating user input using Regular Expressions in C++, but the problem I'm facing is that the code is very repetitive. I'd like to have a function that simply takes in the variable to which the user is inputting a value and its defined RE as arguments, validating these inputs and only then allowing the user to move on to the next input. At the current moment I'm doing this like so:

//input name and validate it
while(1)
{
    std::cout<<"Your Name in that program"<<std::endl;
    std::getline(std::cin, name);
    if(std::regex_match(name,name_pattern))
    {
        break;
    }
    else
    {
        std::cout<<"You have entered incorrectly, please try again"<<std::endl;
    }
}
//input student id and validate it
while(1)
{
    std::cout<<"Your student ID for that program"<<std::endl;
    std::getline(std::cin, studentID);
    if(std::regex_match(studentID,studentID_pattern))
    {
        break;
    }
    else
    {
        std::cout<<"You have entered incorrectly, please try again"<<std::endl;
    }

}

I have a few more inputs that follow the same pattern, but I would like to avoid that.

I'd like to have a function that simply takes in the variable to which the user is inputting a value and its defined RE as arguments, validating these inputs and only then allowing the user to move on to the next input.

Then write that function - you've already done 95% of the work. It would probably look something like this:

std::string GetValidatedInput(const std::regex& validation_pattern,
                              const std::string& prompt_msg) {
    while (true) {
        std::cout << prompt_msg << '\n';

        std::string user_input;
        std::getline(std::cin, user_input);

        if (std::regex_match(user_input, validation_pattern)) {
            return user_input;
        }
        std::cout << "You have entered incorrectly, please try again\n";
    }
}

And call it for each user input you need like this:

std::string name = GetValidatedInput(name_pattern, "Your Name in that program");
std::string studentID = GetValidatedInput(studentID_pattern, "Your student ID in that program");
// ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM