In: Computer Science
Write a method that will have a C++ string passed to it. The string will be an email address and the method will return a bool to indicate that the email address is valid.
Email Validation Rules: ( These rules are not official.)
1) No whitespace allowed
2) 1 and only 1 @ symbol
3) 1 and only 1 period allowed after the @ symbol. Periods can exist before the @ sign.
4) 3 and only 3 characters after the period is required.
*****************************
Program will prompt for an email address and report if it is valid or not according to the rules posted above. The program will loop and prompt me to continue.
*****************************
validate_email.cpp
#include<iostream>
using namespace std;
bool validate(string email)
{
int i;
for(i=0; i<email.length();i++)
{
// If white space found return
false
if(email[i]==' ')
{
return
false;
}
// If @ found the break the
loop
if(email[i]=='@')
{
i++;
break;
}
}
for(; i<email.length();i++)
{
// If another @ or a white space
found the return false
if(email[i]=='@' || email[i]=='
')
{
return
false;
}
// If period found then break the
loop
if(email[i]=='.')
{
i++;
break;
}
}
// If number of characters after period is not 3 then
return false
if(email.length()-i!=3)
{
return false;
}
for(; i<email.length(); i++)
{
// If another @ or period or a
white space found then return false
if(email[i]=='@' || email[i]=='.'
|| email[i]==' ')
{
return
false;
}
}
// Execution comes here if email address is
valid
return true;
}
int main()
{
string email;
cout<<"Enter email address: ";
// User input
getline(cin,email);
// Function calling and output printing
validate(email)==1?cout<<"Valid":cout<<"Invalid";
return 0;
}
output screenshot: