email validation

Hi all,

I am trying to learn c++ and this is what I have come up with. I want to apply email validation and the constraints that I want to put are -
1. first place should have alphabet only.
2. before @ there can be any alphabet, digit, _ or .
3. After @ is detected .com or .co.in should come next.

Is my approach right?


#include<iostream>
#include<string>
#include<cctype>
using namespace std;

int main()
{

void getemail();
return 0;
}




void getemail()
{

string email;
int flag=0;

cout<<"enter your email id: ";
cin>>email;


for(unsigned int pos=0; pos<email.size();pos++)
{
if(isalpha(email[pos]))
{
flag=0;
}

while(!email.find(pos=='@'))
{
if(email[pos]>='a' && email[pos]<='z' || email[pos]>='A' && email[pos]<='Z' || email[pos]='_' || email[pos]='.' || email[pos]>='0' && email[pos]<='9')

flag=0;
}

for(pos>1; pos<email.size())
{
if(email.find('@'))
{
flag=0;
}

while(email.find('@'))
{
pos++;
if(isalnum(email.find(pos)=='.com'||'.co.in'))
flag=0;
}
}

}

if(!flag=0)
{
cout<<"\nEmail ID is invalid"<<endl;
}

}
Last edited on
You do know that your constraints will not allow many legal e-mail addressess, do you?

I really want to point to standard C++ regex parser and this ( http://ex-parrot.com/~pdw/Mail-RFC822-Address.html ) regex (or that, if you are not crazy http://forums.asp.net/post/1801198.aspx :))

But for now I just tell you about isalnum() and other useful functions in <cctype>: http://cplusplus.com/reference/cctype/
Thanks for replying. Yes I know that my constraints will not accept many of the valid email ids but I need to start from somewhere and hence I thought of starting with this and later I can make changes(first I need to learn how to make code for validation, right?)

I am not supposed to submit this code or use it anywhere, just trying to learn. :)

Can you please help me in correcting the errors? :) I know my code is really stupid and probably of no use. :P

Thanks for the links. I already saw parrot.com link, will go through http://forums.asp.net/post/1801198.aspx as well. :)
Use parentheses in conditions. I believe operator precedence will make your code to behave differently than you expect.

Replace email[pos]>='a' && email[pos]<='z' || ... with isalnum(email[pos]) and other useful functions.
Topic archived. No new replies allowed.