请注意,此代码并不是完美的:用户可以说他们的名字是“ASF W jweo标迪我们岙”或其他一些胡言乱语,甚至更糟,只是一堆空间。我们可以稍微的精炼我们的验证标准只接受,至少包含一个字符,最多一个空字符串地址本。
现在让我们来看看另一个例子,我们将要求用户输入自己的电话号码。不同的用户的名字,这是可变长度的,其中验证标准是相同的每一个字,一个电话号码是一个固定长度的但有效标准,根据不同的字符的位置。因此,我们要采取不同的方法来验证我们的电话号码输入。在这种情况下,我们要写一个函数,将检查用户的输入是否与预定的模板匹配。模板将工作如下:
一个#将匹配在用户输入任何数字。
“将匹配在用户输入任何字母。
一个_将匹配任何空白。
一个?将匹配任何东西。
否则,在用户输入的字符和模板必须完全匹配。
所以,如果我们要求功能相匹配的模板”(# # #)# # # - # # # #”,这意味着我们期望用户输入一个'('字符,三个数字,一个')'字,一个空间,三个数字,一个破折号,四号。如果这些事情不匹配,输入将被拒绝。
下面的代码是:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
bool InputMatches(string strUserInput, string strTemplate)
{
if (strTemplate.length() != strUserInput.length())
return false;
// Step through the user input to see if it matches
for (unsigned int nIndex=0; nIndex < strTemplate.length(); nIndex++)
{
switch (strTemplate[nIndex])
{
case '#': // match a digit
if (!isdigit(strUserInput[nIndex]))
return false;
break;
case '_': // match a whitespace
if (!isspace(strUserInput[nIndex]))
return false;
break;
case '@': // match a letter
if (!isalpha(strUserInput[nIndex]))
return false;
break;
case '?': // match anything
break;
default: // match the exact character
if (strUserInput[nIndex] != strTemplate[nIndex])
return false;
}
}
return true;
}
int main()
{
string strValue;
while (1)
{
cout << "Enter a phone number (###) ###-####: ";
getline(cin, strValue); // get the entire line, including spaces
if (InputMatches(strValue, "(###) ###-####"))
break;
}
cout << "You entered: " << strValue << endl;
}