用C++进行电子邮件验证

ETE*_*ION 5 c++ email validation c-strings

好的,所以我正在尝试制作一个允许用户输入电子邮件的程序.如果符合两项规定,他们的电子邮件将被视为有效: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 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;
}
Run Code Online (Sandbox Code Playgroud)

gon*_*jay 12

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

#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;
}
Run Code Online (Sandbox Code Playgroud)

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

  • “现在你有两个问题”,由 Stack Overflow 的创建者提供!http://blog.codinghorror.com/regular-expressions-now-you-have-two-problems/ (5认同)

Sam*_*hik 3

这里的主要问题是,这应该是一个 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;
}
Run Code Online (Sandbox Code Playgroud)

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