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 "@". 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.
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
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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With