好的,所以我正在尝试制作一个允许用户输入电子邮件的程序。如果满足以下两个规定,他们的电子邮件将被视为有效:A. 必须在某处有一个“@”符号,B. 在“@”之后必须有一个句点。我大部分时间都把代码写下来了,但是在验证“@”符号之前有句点的电子邮件时我遇到了一些困难。如果它们在“@”符号之前有句点,则它们被认为是有效的,但它们不应该是。例如,输入 text.example@randomcom
被认为是有效的。
谁能帮我弄清楚我做错了什么?先感谢您!
#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;
}
原文由 ETERNAL OBLIVION 发布,翻译遵循 CC BY-SA 4.0 许可协议
为什么不使用正则表达式?
http://en.cppreference.com/w/cpp/regex