-1

如何检查用户是否输入了电子邮件格式的字符串,

例如Ted@Ted.com

我想检查是否有“@”和“。”

除了使用 ispunct 函数

4

2 回答 2

2

您可以使用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;
}

但通常解析电子邮件地址的免责声明:这是一个非常复杂的主题,因为有效的电子邮件地址是一头奇怪的野兽。检查RFC 5322以了解什么是有效地址。

于 2013-02-16T18:00:37.317 回答
1

使用正则表达式,您可以评估

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

它几乎匹配所有合法的电子邮件地址。看到这个问题

如果您使用的是 C++11,则可以使用std::regex,否则您必须使用 3rdparty 正则表达式解析器,例如boost::regex

于 2013-02-16T18:02:07.370 回答