[英]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?
我正在使用 C++ 中的正則表達式驗證用戶輸入,但我面臨的問題是代碼非常重復。 我想要一個 function,它只接受用戶輸入值的變量及其定義的 RE 為 arguments,驗證這些輸入,然后才允許用戶繼續下一個輸入。 目前我正在這樣做:
//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;
}
}
我還有一些遵循相同模式的輸入,但我想避免這種情況。
我想要一個 function,它只接受用戶輸入值的變量及其定義的 RE 為 arguments,驗證這些輸入,然后才允許用戶繼續下一個輸入。
然后寫下 function - 你已經完成了 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");
// ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.