#include<algorithm> // std::equal#include<cctype> // std::isdigit, std::isspace, std::isalpha#include<iostream>#include<map>#include<ranges>#include<string>#include<string_view>boolinputMatches(std::string_viewinput,std::string_viewpattern){if(input.length()!=pattern.length()){returnfalse;}// This table defines all special symbols that can match a range of user input// Each symbol is mapped to a function that determines whether the input is valid for that symbolstaticconststd::map<char,int(*)(int)>validators{{'#',&std::isdigit},{'_',&std::isspace},{'@',&std::isalpha},{'?',[](int){return1;}}};// Before C++20, use// return std::equal(input.begin(), input.end(), pattern.begin(), [](char ch, char mask) -> bool {// ...returnstd::ranges::equal(input,pattern,[](charch,charmask)->bool{if(autofound{validators.find(mask)};found!=validators.end()){// 找到可匹配的模式,调用对应的校验函数return(*found->second)(ch);}else{// 没有找到匹配的模式,此时要求字符精确匹配return(ch==mask);}});}intmain(){std::stringphoneNumber{};do{std::cout<<"Enter a phone number (###) ###-####: ";std::getline(std::cin,phoneNumber);}while(!inputMatches(phoneNumber,"(###) ###-####"));std::cout<<"You entered: "<<phoneNumber<<'\n';}
#include<iostream>#include<limits>intmain(){intage{};while(true){std::cout<<"Enter your age: ";std::cin>>age;if(std::cin.fail())// no extraction took place{std::cin.clear();// reset the state bits back to goodbit so we can use ignore()std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');// 从流中清除错误的输入continue;// try again}std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');// 从输入流中剔除多余的输入if(age<=0)// make sure age is positivecontinue;break;}std::cout<<"You entered: "<<age<<'\n';}
#include<iostream>#include<limits>intmain(){intage{};while(true){std::cout<<"Enter your age: ";std::cin>>age;if(std::cin.fail())// no extraction took place{std::cin.clear();// reset the state bits back to goodbit so we can use ignore()std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');// clear out the bad input from the streamcontinue;// try again}std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');// clear out any additional input from the streamif(std::cin.gcount()>1)// if we cleared out more than one additional character{continue;// we'll consider this input to be invalid}if(age<=0)// make sure age is positive{continue;}break;}std::cout<<"You entered: "<<age<<'\n';}