强制输入通过验证检查

Forcing input through validation check

本文关键字:验证 检查 输入      更新时间:2023-10-16

我们创建了一个验证检查,以便输入只能是字母字符。虽然它按预期工作,但我和我的朋友都遇到了一个奇怪的症状,即使代码显然(至少对我们来说(不允许他们这样做,您也可以强制通过验证。

运行以下代码,然后按 [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                                                                                              
}