强制输入通过验证检查
Forcing input through validation check
我们创建了一个验证检查,以便输入只能是字母字符。虽然它按预期工作,但我和我的朋友都遇到了一个奇怪的症状,即使代码显然(至少对我们来说(不允许他们这样做,您也可以强制通过验证。
运行以下代码,然后按 [enter] 或随机垃圾大约十几次并输入不可接受的输入(例如321-(将导致程序退出验证。是某种固有的限制还是我们错过了代码?
即使在将代码剥离到裸验证后也会导致症状,尽管它似乎确实有不同的限制,具体取决于机器。一些计算机让它在 3-4 次暴力强迫后偷偷溜走,而 c9.io 则承受了大约十几次。
我的验证循环看起来确实很混乱,但我之前在较小的 for 循环中也经历过。到目前为止,我注意到的唯一相似之处是 getline((
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
//prototypes
void validateUserName(string &name);//validate name
//main function
int main()
{
//initialize
ifstream file;
string username; //holds username which serve as file name
//first prompt
cout<< "Enter your name and press <ENTER>";
getline(cin, username);
//call functions
validateUserName(username);
//begin shutdown
cout << "good-bye" << endl;
cin.get();
}
void validateUserName(string &name){
int errCount = 0;
int i=0;
do
{
errCount = 0;
i=0;
//go thru each character of the name to count non-alphabetic character
while (name[i])
{
if ( !isalpha(name[i]) )
errCount++;
i++;
}
if (errCount > 0 || name.empty() )
{
//prompt user again alerting them of error
cout << "Invalid entry, try again" << endl;
getline(cin, name);
}
}
while (errCount > 0 || name.empty() );//the validation loop doesn't end until user enters acceptable entry
name+=".txt"; //appended file type
}
当你从第二个cin 出来时,name
不再是空的。因此,不满足第二个条件,您退出主 while 循环。一个快速的解决方法是在最终条件中增加 errCount:
if (errCount > 0 || name.empty() )
{
errCount++;
cout << "Invalid entry, try again" << endl;
getline(cin, name);
}
虽然这不是您问题的一部分,但我建议您使用string::size()
而不是检查空字符。我不认为getline添加了这个,所以你可能正在处理未定义的行为。
void validateUserName(string &name)
{
int errCount = 0;
do
{
errCount = 0;
//go thru each character of the name to count non-alphabetic character
for (int i = 0; i < name.size() && !name.empty(); i++)
{
if ( !isalpha(name[i]) )
{
errCount++;
break;
}
}
if (errCount > 0 || name.empty() )
{
errCount++;
//prompt user again alerting them of error
cout << "Invalid entry, try again" << endl;
getline(cin, name);
}
}
while (errCount > 0 || name.empty() );//the validation loop doesn't end until user enters acceptable entry
}
相关文章:
- valgrind-hellgrind与泄漏检查的结果不同
- C++模板来检查友元函数的存在
- 检查输入是否不是整数或数字
- 正在尝试了解输入验证循环
- 如何在C++中检查2D数组中负值的输入验证
- 检查节点的输入验证的整数
- 验证(使用 static_assert)元组类型是否遵循某种顺序(有状态编译时检查)
- 强制输入通过验证检查
- 如何检查验证
- JSON 请求在名称验证检查期间忽略''
- 检查串行端口信息/描述以验证正确的端口
- 在数组中输入5个元素,检查验证,然后输出C++
- 验证代码以检查数字是否为回文
- 是否可以使用Boost概念检查库验证方法返回类型
- 如何实现旋转框的验证器来检查是否(n mod k == 0)
- 是否执行decltype内的表达式,或者只是检查是否验证
- c++模板检查类型验证
- 数组边界检查和输入验证
- QT快速或c++检查有效的电子邮件输入(电子邮件格式验证器)
- 如何进行良好的验证来检查输入是数字