-1

How do i check if user input a string with an email format,

E.g. Ted@Ted.com

I want to check if there's an "@" and "."

other than using ispunct function

user1745860
  • 207
  • 1
  • 5
  • 11

2 Answers2

2

You can use std::string::find_first_of.

// Check that the string contains at least one '@' and a '.'
// after it. This will have lots of false negatives (but no
// false negative), like "a@b@c.com" or "toto@com.".
bool is_email(std::string const& address) {
    size_t at_index = address.find_first_of('@', 0);
    return at_index != std::string::npos 
        && address.find_first_of('.', at_index) != std::string::npos;
}

But usual disclaimer with parsing email addresses: this is a really complex topic, because a valid email address is a strange beast. Check RFC 5322 for specification of what is a valid address.

Sylvain Defresne
  • 42,429
  • 12
  • 75
  • 85
1

Using regular expressions, you can evaluate against

^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$

which matches nearly all legal email addresses. See this question

If you're using C++11 you can use std::regex, otherwise you'll have to use a 3rdparty regex parser such as boost::regex

Community
  • 1
  • 1
eladidan
  • 2,634
  • 2
  • 26
  • 39