请注意,这个程序是预期的用户输入一个整数。然而,如果用户输入非数字数据,如“亚历克斯”,CIN将无法提取任何管理,并将设置failbit。
如果发生了一个错误,一个流将比其他任何goodbit,对该流将被忽略,进一步的操作流。这种情况可以通过调用clear()功能清除。
输入验证
输入验证是检查用户是否输入满足一定的标准过程。输入验证一般可以分为两种类型:字符串和数字。
字符串的验证,我们接受的所有用户输入一个字符串,然后接受或拒绝该字符串取决于它是否是适当地格式。例如,如果我们要求用户输入一个电话号码,我们可能想确保他们有十位数据输入。在大多数语言中(尤其是脚本语言,如Perl和PHP),这是通过正则表达式。然而,C++没有内置的正则表达式的支持(这是所谓的C + +下修改),因此这通常是通过检查每个字符的字符串,以确保其符合一定的标准。
数值验证,我们通常涉及确定数量的用户进入的是在一个特定的范围内(如0和20之间)。然而,不像字符串验证,用户就有可能进入的东西并不在所有的数字,我们需要处理这些案件太。
来帮助我们,C++提供了许多有用的功能,我们可以用以确定特定字符是数字或字母。以下功能活在cctype头:
#include <cctype>
#include <string>
#include <iostream>
using namespace std;
while (1)
{
// Get user's name
cout << "Enter your name: ";
string strName;
getline(cin, strName); // get the entire line, including spaces
bool bRejected=false; // has strName been rejected?
// Step through each character in the string until we either hit
// the end of the string, or we rejected a character
for (unsigned int nIndex=0; nIndex < strName.length() && !bRejected; nIndex++)
{
// If the current character is an alpha character, that's fine
if (isalpha(strName[nIndex]))
continue;
// If it's a space, that's fine too
if (strName[nIndex]==' ')
continue;
// Otherwise we're rejecting this input
bRejected = true;
}
// If the input has been accepted, exit the while loop
// otherwise we're going to loop again
if (!bRejected)
break;