【发布时间】:2021-03-26 00:21:32
【问题描述】:
我正在使用 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;
}
}
我还有一些遵循相同模式的输入,但我想避免这种情况。
【问题讨论】: