C++电子邮件验证

Email validation in C++

本文关键字:验证 电子邮件 C++      更新时间:2023-10-16

好的,所以我正在尝试制作一个允许用户输入电子邮件的程序。如果满足两个规定,他们的电子邮件将被视为有效:A.那里的某个地方必须有一个"@"符号,B.在"@"之后必须有一个句点。我大部分都记下了代码,但在验证在"@"符号之前有句点的电子邮件时遇到了一些困难。如果它们在"@"符号之前有句点,则它们被认为是有效的,但它们不应该是有效的。例如,输入text.example@randomcom被视为有效。

谁能帮我弄清楚我做错了什么?提前谢谢你!

#include <iostream>
#include <cctype>
#include <cstring>
using namespace std;
int main()
{
    int x = 25; //random size enough to hold contents of array plus one for               null terminator
    char input[x]; //array to hold input
    int sizeOf; //holds length of input array
    char* ptr = nullptr; //pointer
    char* ptr2 = nullptr; //pointer
    cout << "Enter your email addressn";
    cin.getline(input,x);
    sizeOf = strlen(input);
    for(int i = 0; i < sizeOf; i++)
    {
        ptr= strstr(input, "@"); //searches input array for "@" string
        if(ptr != nullptr) 
        {
            break;
        }
    }
    for(int i = 0; i < sizeOf; i++)
    {
        ptr2 = strstr(input, "."); //searches input array for "." string
        if(ptr2 != nullptr && &ptr2 > &ptr)
        {
            break;
        }
    }
    if(ptr != nullptr) //validates input of "@" sign
    {
        if(ptr2 != 0 && &ptr2 < &ptr) 
            {
                cout << "Email accepted.n";
            }
        else
            {
                cout << "Missing . symbol after @n";
            }
    }
    else
    {
        cout << "Missing @ symboln";
    }

return 0;
}

为什么不使用正则表达式?

#include <iostream>
#include <string>
#include <regex>
bool is_email_valid(const std::string& email)
{
   // define a regular expression
   const std::regex pattern
      ("(\w+)(\.|_)?(\w*)@(\w+)(\.(\w+))+");
   // try to match the string with the regular expression
   return std::regex_match(email, pattern);
}
int main()
{
    std::string email1 = "text.example@randomcom";
    std::cout << email1 << " : " << (is_email_valid(email1) ?
      "valid" : "invalid") << std::endl;
}

http://en.cppreference.com/w/cpp/regex

static bool IsEmailAddress(const std::string& str)
{
    // Locate '@'
    auto at = std::find(str.begin(), str.end(), '@');
    // Locate '.' after '@'
    auto dot = std::find(at, str.end(), '.');
    // make sure both characters are present
    return (at != str.end()) && (dot != str.end());
}

这里的主要问题是这应该是一个C++程序,但相反,它变成了一个C程序。 strstr (( 和 strlen (( 是 C 库函数。

在现代C++我们使用std::string、迭代器和算法,这使得整个任务更短,更容易摸索。也无需担心缓冲区溢出:

#include <string>
#include <algorithm>
// Your main() declaration here, etc...
std::string input;
std::cout << "Enter your email address" << std::endl;
std::getline(std::cin, input);
auto b=input.begin(), e=input.end();
if (  (b=std::find(b, e, '@')) != e &&
      std::find(b, e, '.') != e )
{
    std::cout << "Email accepted" << std::endl;
}
else
{
    std::cout << "Email rejected" << std::endl;
}

现在,这不是更短,更容易解析吗?

使用std::string,而不是那种讨厌的固定大小的 C 字符串。

int main()
{
    string input;
    cout << "Enter your email addressn";
    getline(cin, input);
    size_t at = input.find('@');
    if (at == string::npos)
    {
        cout << "Missing @ symboln";
        return 1;
    }
    size_t dot = input.find('.', at + 1);
    if (dot == string::npos)
    {
        cout << "Missing . symbol after @n";
        return 2;
    }
    cout << "Email accepted.n";
    return 0;
}

我改进了用于检查定位部分和域长度的dshvets1代码:

bool IsEmailAddress(const std::string& str)
{
        if (str.size() > 150)
            return false;
        const auto at = std::find(str.cbegin(), str.cend(), '@');
        const auto dot = std::find(at, str.cend(), '.');
        if((at == str.cend()) || (dot == str.cend()))
            return false;
        if (std::distance(str.cbegin(), at) < 1) //~@ - is minimal local part
            return false;
        if(std::distance(at, str.cend()) < 5 )  //@i.ua - is minimal domain
            return false;
        return true;
}

您对不反映真实电子邮件地址的有效电子邮件地址有非常严格和具体的规则。假设这是故意的,我看到的主要问题是你在不需要的时候编写循环。库函数strstr()为您执行循环。您只需将字符串传递给它,它将遍历它以查找char

因此,让函数为您查找,您可以像这样划分和征服问题:

bool is_valid(char const* email)
{
    auto at_pos = std::strchr(email, '@');
    if(at_pos == nullptr)
        return false; // did not find an '@' (rule A violation)
    auto dot_pos = std::strchr(email, '.');
    if(dot_pos == nullptr)
        return false; // did not find an '.' (rule B violation)
    if(dot_pos < at_pos)
        return false; // '.' found before '@' (rule B violation)
    return true; // all rules followed!
}

尝试使用以下方法。

bool ValidateEmail(string email)
{
    if (regex_match(email, regex("([a-z]+)([_.a-z0-9]*)([a-z0-9]+)(@)([a-z]+)([.a-z]+)([a-z]+)"))) 
        return true;
    return false;
}

Peace of Cake Regex 是虚幻引擎C++

bool IsValidEmailAddressFormat(const FString& String)
{
    const FRegexPattern Pattern(TEXT("^([a-z0-9]+)((\.|-|_)([a-z0-9])+)*@([a-z0-9]+)(\.([a-z0-9]{2,8}+))+$"));
    FRegexMatcher Matcher(Pattern, String);
    return Matcher.FindNext();
}

当您搜索@字符时,然后您可以从i变量的先前值开始,而不是从字符串的开头搜索'.。

注意:- 我没有在这个和所有其他情况下考虑太多。

它应该是:

if(ptr2 != 0 && &ptr2 >&ptr)

而不是:

if(ptr2 != 0 && &ptr2 < &ptr)
//Program to validate email
#include<iostream>                 //header files
#include<string>
using namespace std;
int strLength(char str[]);
int email_check(char str[])
{                                               //function to check the conditions for email
int size,pos=0,pos1=0,c=0;
size=strLength(str);
if((str[0]>='a'&& str[0]<='z')||(str[0]>='A'&& str[0]<='Z'))  //first char should be an alphabet
{
for(int i=0;i<size;i++)
{
if((str[i]>='a'&& str[i]<='z')||(str[i]>='0' && str[i]<='9') || str[i]=='.'||str[i]=='_'||str[i]=='-'||str[i]=='#'||str[i]=='@')                                         //combination of characters allowed
{
if(str[i]=='.'||str[i]=='_'||str[i]=='-'||str[i]=='#'||str[i]=='@')    // symbol encountered 
{
if((str[i+1]>='a'&&str[i+1]<='z')||(str[i+1]>='0' &&str[i+1]<='9')) //no 2 repeated symbols
{
if(str[i]=='@')                       //@ encountered, so domain part begins
pos=i;                                  //pos is the position where domain begins
}
else
return 0;
}
}
else
return 0;
}
}
else
return 0;
if(pos==0)
return 0;
else
{
for(int j=pos+1;j<size;j++)
{
if(str[pos+1]>='a'&&str[pos+1]<='z')
{
if(str[j]=='.') 
pos1=j;
}
else
return 0;
}
}
if(pos1==0)
return 0;
else
{
for(int k=pos1+1;k<size;k++)
{
if(str[k]>='a'&&str[k]<='z')
c++;
else
return 0;
}
if(c>=2)
return 1;
else
return 0;
}                                           
}                                           //end of function
int main()
{
int c;
char email[100],ch;
do
{
cout<<"nEnter email: ";
cin.get(email , 100)    ;                                 //accepting email from user
c=email_check(email);
if(c==1)                     //if all criteria matched
{
cout<<"nemail accepted...n";
cout<<"nYour email address is: ";
puts(email);
break;
}
else                               //criteria not matched
{
cout<<"nInvalid email";
cout<<"nnWant to re-enter email(y/n): ";
cin>>ch;
}
}while(ch=='y'||ch=='Y');   //user is asked to enter again until the choice is yes
return 1;
}

int strLength(char str[]) {
    int k = 0;
    for(k = 0 ; ;k++){
        if(str[k] == '')
            break;
    }
    return k;
}