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;
}
[email protected]
is a modest length address that is too long by 4 characters for your code. This is why fixed-length C style buffers are really bad news. – Academe<cstring>
? Or can you use<algorithm>
and<regex>
? – Tricksy