微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何创建一个验证函数,该函数将根据特定输入及其定义的正则表达式验证用户的输入?

如何解决如何创建一个验证函数,该函数将根据特定输入及其定义的正则表达式验证用户的输入?

我正在使用 C++ 中的正则表达式验证用户输入,但我面临的问题是代码非常重复。我想要一个函数,它只接受用户输入值的变量及其定义的 RE 作为参数,验证这些输入,然后才允许用户继续下一个输入。目前我正在这样做:

//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;
    }

}

我还有一些遵循相同模式的输入,但我想避免这种情况。

解决方法

我想要一个函数,它只接受用户输入值的变量及其定义的 RE 作为参数,验证这些输入,然后才允许用户继续下一个输入。

然后编写该函数 - 您已经完成了 95% 的工作。它可能看起来像这样:

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";
    }
}

并为您需要的每个用户输入调用它,如下所示:

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。