简体   繁体   English

C++ 中的电子邮件验证

[英]Email validation in C++

Okay so I'm trying to make a program which allows user to input their email.好的,所以我正在尝试制作一个允许用户输入电子邮件的程序。 Their email will be considered valid if two stipulations are met: A. there must be an "@" sign somewhere in there and B. there must be a period after the "@".如果满足两个规定,他们的电子邮件将被视为有效:A. 必须在其中某处有一个“@”符号,并且 B. 在“@”之后必须有一个句点。 I got the code down for the most part, but I am having some difficulty when it comes to validating emails that have a period before the "@" sign.我大部分时间都得到了代码,但是在验证“@”符号之前有句点的电子邮件时,我遇到了一些困难。 If they have the period before the "@" sign they are considered valid, but they shouldn't be.如果它们在“@”符号之前有句点,则它们被认为是有效的,但它们不应该是有效的。 For example, entering text.example@randomcom is considered valid.例如,输入text.example@randomcom被认为是有效的。

Can anyone help me figure out what I did wrong?谁能帮我弄清楚我做错了什么? Thank you in advance!提前谢谢你!

#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 address\n";
    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 @ symbol\n";
    }



return 0;
}

Why not use regex?为什么不使用正则表达式?

#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 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());
}

The main problem here is that this is supposed to be a C++ program, but, instead, it became a C program.这里的主要问题是这应该是一个 C++ 程序,但它变成了一个 C 程序。 strstr () and strlen () are C library functions. strstr () 和strlen () 是C 库函数。

In modern C++ we use std::string , iterators, and algorithms, which make the whole task much shorter, and easier to grok.在现代 C++ 中,我们使用std::string 、迭代器和算法,这使得整个任务更短,更容易理解。 And there's no need to worry about buffer overflows, either:并且无需担心缓冲区溢出,或者:

#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;
}

Now, isn't that shorter, and easier to parse?现在,这不是更短,更容易解析吗?

Use std::string , not that nasty fixed-size C string stuff.使用std::string ,而不是那种讨厌的固定大小的 C 字符串。

int main()
{
    string input;
    cout << "Enter your email address\n";
    getline(cin, input);

    size_t at = input.find('@');
    if (at == string::npos)
    {
        cout << "Missing @ symbol\n";
        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;
}

I have improved dshvets1 code for checking locat part and domain length:我改进了用于检查 locat 部分和域长度的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;
}

You have very restricted and specific rules about valid email addresses that are not reflective of real email addresses.您对不反映真实电子邮件地址的有效电子邮件地址有非常严格和具体的规则。 Assuming that's intentional, the main problem I see is you are writing loops when you do not need to.假设这是故意的,我看到的主要问题是您在不需要时编写循环。 The library function strstr() does the looping for you.库函数strstr()为您执行循环。 You just pass it the string and it will loop through it looking for the char .您只需将字符串传递给它,它就会遍历它以查找char

So, letting the function do the finding for you, you can divide and conquer the problem like this:所以,让函数为你做发现,你可以像这样分而治之:

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!
}

Try using the below method.尝试使用以下方法。

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;
}

when you search the @ character, then after that instead of searching '.'当您搜索 @ 字符时,然后在此之后而不是搜索 '.' from beginning of the string, you can start from the previous value of i variable.从字符串的开头,您可以从 i 变量的前一个值开始。

Note:- I did not think much on this and all other cases.注意:-我对此和所有其他情况都没有考虑太多。

It should be:应该是:

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

instead of:而不是:

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<<"\n\nWant 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] == '\0')
            break;
    }
    return k;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM