Introduction
Email addresses are essential for communication in the digital world. However, ensuring that an email address is valid and properly formatted is critical before using it in any system. This program aims to validate whether a given email address conforms to a standard email format, such as “example@domain.com“. It checks for the presence of essential components like the “@” symbol, a domain name, and the dot separator in the domain part.
Objective
The objective of this program is to validate if a given string is a properly formatted email address. This ensures that the input follows the basic rules of email syntax and can be used effectively in email-related applications or systems.
Code Implementation
#include
#include
#include
using namespace std;
// Function to validate email address using regular expression
bool isValidEmail(const string& email) {
// Regular expression for email validation
const regex emailPattern("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$");
// Check if the email matches the pattern
return regex_match(email, emailPattern);
}
int main() {
string email;
// Taking input from the user
cout << "Enter an email address to validate: "; cin >> email;
// Validate the email
if (isValidEmail(email)) {
cout << "The email address '" << email << "' is valid!" << endl;
} else {
cout << "The email address '" << email << "' is not valid." << endl;
}
return 0;
}
Explanation of the Program
This program uses the C++ Standard Library, specifically the regex
class, to validate an email address. Here’s the breakdown:
- Regex pattern: The regular expression
^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
is designed to match a valid email structure. It checks that:- The username part can include alphanumeric characters, dots, underscores, percent signs, plus signs, and hyphens.
- The “@” symbol separates the username and domain parts.
- The domain part includes alphanumeric characters and dots.
- The top-level domain (TLD) part must have at least two alphabetic characters.
- Function
isValidEmail()
: This function checks if the input email matches the specified pattern usingregex_match()
. - Main Function: It prompts the user to enter an email address, then calls
isValidEmail()
to validate the input. If the email is valid, a success message is displayed; otherwise, it shows an error.
How to Run the Program
To run this program:
- Ensure you have a C++ compiler (e.g., GCC, Clang) installed on your system.
- Copy the code into a text editor and save the file with a
.cpp
extension (e.g.,validate_email.cpp
). - Open a terminal or command prompt and navigate to the directory containing the file.
- Compile the program using a command like
g++ -o validate_email validate_email.cpp
. - Run the compiled program using
./validate_email
(on Linux/macOS) orvalidate_email.exe
(on Windows).