【发布时间】:2019-05-03 16:22:29
【问题描述】:
我正在尝试在不使用正则表达式库的情况下创建电子邮件验证程序。在我的一个函数中,我想返回一个布尔值来检查电子邮件地址中是否有 @ 符号以及它是否处于有效位置(@ 符号不能是字符串的前三个字符之一)。但是我遇到了问题,因为每次我通过输入带有@符号无效位置的电子邮件地址来运行程序时,它一直告诉我该电子邮件是有效的。请帮忙!
valid = checkEmail(email); //function call
if(valid == true)
cout << "Your email is valid!" << endl;
else
cout << "Your email is invalid!" << endl;
bool checkEmail(string email)
{
int counter;
int length;
bool firstThree; //checks to make sure @ is not in the first three chars
counter = 0;
length = email.length();
firstThree = false;
for(int i = 0; i < length; i++)
{
if(email[i] == '@')
counter++;
}
for(int y = 0; y < length; y++)
{
if(email[0] == '@' || email[1] == '@' || email[2] == '@')
firstThree = true;
else
firstThree = false;
}
cout << "\n" << counter << endl; //check to see if counter works
if(counter != 1 && firstThree == true)
return false;
else
return true;
}
【问题讨论】:
-
听起来您可能需要学习如何使用调试器来单步调试您的代码。使用好的调试器,您可以逐行执行您的程序,并查看它与您期望的偏差在哪里。如果您要进行任何编程,这是必不可少的工具。进一步阅读:How to debug small programs 和 Debugging Guide
-
if(counter != 1 && firstThree == true)仅当您的电子邮件没有 @ ind 时才会返回 false。AND 如果 @ 位于前三个字符中。另请注意,围绕 firstThree 检查的 for 循环没有任何用处。 -
还可以查看std:.string::find_first_of,它返回字符串的第一次出现。有了它,您的任务将非常简单。当你想做类似的事情时,也可以看看
std::basic_string,因为它提供了许多有用的实用程序