Introduction:
Email address validation is a common task in many software applications. It helps ensure that the input follows a standard email format and prevents errors during communication. A properly formatted email address consists of a local part (username), the @ symbol, and a domain part (such as domain.com). In this task, we will write a C program to validate if a given string is a valid email address based on certain rules.
Objective:
The goal of this program is to take a string input from the user, check if it follows the structure of a valid email address (e.g., username@domain.com), and provide feedback on its validity.
Program Code
#include #include #include // Function to validate if the given email address is properly formatted int isValidEmail(char *email) { int atCount = 0; int dotCount = 0; int len = strlen(email); // Check if email is empty or too short if (len < 5) { return 0; // Invalid email } // Iterate through the email to check conditions for (int i = 0; i < len; i++) { char ch = email[i]; // Check if there is exactly one '@' symbol if (ch == '@') { atCount++; } // Check if there is at least one '.' after the '@' if (ch == '.') { dotCount++; } // Ensure the email contains only valid characters if (!(isalnum(ch) || ch == '@' || ch == '.' || ch == '-' || ch == '_')) { return 0; // Invalid email } } // Valid email should have exactly one '@' and at least one '.' after '@' if (atCount != 1 || dotCount == 0) { return 0; // Invalid email } return 1; // Valid email } int main() { char email[100]; // Prompt user for email input printf("Enter an email address to validate: "); scanf("%s", email); // Validate the email and display result if (isValidEmail(email)) { printf("The email address is valid.\n"); } else { printf("The email address is invalid.\n"); } return 0; }
Program Explanation
The program follows a simple structure:
- isValidEmail function: This function takes the email address as input and checks for common validation conditions. It counts occurrences of ‘@’ and ‘.’ characters, ensures that the email contains only valid characters, and checks that there is exactly one ‘@’ and at least one ‘.’ after ‘@’. If these conditions are met, it returns 1 (valid email); otherwise, it returns 0 (invalid email).
- main function: This is where the program starts. The user is prompted to enter an email address, and the program calls the
isValidEmail
function to check the validity of the email. Based on the result, it displays either a success or failure message.
How to Run the Program
- Save the code in a file with a
.c
extension, such asvalidate_email.c
. - Compile the program using a C compiler, for example:
gcc -o validate_email validate_email.c
- Run the program using the following command:
./validate_email
- Enter an email address when prompted, and the program will validate it.