![]()
Cleaned up name function + email function
-------------- cut and paste the code below into your editor -----------------------
#include <string.h>
#include <stdio.h>
#include <ctype.h>
int getEmail(char * userEmail);
int getName(char * name, char * prompt);
int getPhoneNumber(char * userPhone);
void main()
{
char userEmail[80];
char firstName[80];
char lastName[80];
char userPhone[80];
int nameValid;
int emailValid;
do {
nameValid = getName(firstName,"Enter first name: ");
if (nameValid != 1) {
printf("You entered an invalid name, try again\n");
}
}
while (nameValid == 0);
do {
nameValid = getName(lastName,"Enter last name: ");
if (nameValid != 1) {
printf("You entered an invalid name, try again\n");
}
}
while (nameValid == 0);
// to get here, we now have a good first and last name
do {
emailValid = getEmail(userEmail);
if (emailValid != 1) {
printf("You entered an invalid email, try again\n");
}
}
while (emailValid == 0);
}
int getName(char * charArray, char * msg)
{
int entryValid = 1; // presume entry is valid until we disprove it
int entryLength,i;
printf(msg);
gets(charArray);
printf("You entered: %s\n",charArray);
// strlen gives the length of an array of characters
entryLength = strlen(charArray); // "John" strlen = 4
// if user just pressed 'enter', this is not valid
if (entryLength == 0) {
return 0;
}
// to get here, something must have been entered
// look at each character individually
entryValid = 1;
for (i = 0; i < entryLength; i++) { // "John" i = 0,1,2,3
// if a space is in the name, invalidate it
if (charArray[i] == ' ') {
entryValid = 0;
}
// check if entry is a character
// if (!x) is the same as if (x == 0)
if (!isalpha(charArray[i])) { // !0 is equal to 1
entryValid = 0;
}
}
return entryValid;
}
int getEmail(char * charArray)
{
int entryValid = 1; // presume entry is valid until we disprove it
int entryLength,i;
printf("Enter the email address: ");
gets(charArray);
printf("You entered: %s\n",charArray);
// strlen gives the length of an array of characters
entryLength = strlen(charArray); // "John" strlen = 4
// if user just pressed 'enter', this is not valid
if (entryLength == 0) {
return 0;
}
// to get here, something must have been entered
// look at each character individually
// valid email rules:
// must not contain spaces
// must contain both the @ and the '.'
entryValid = 1;
// strchr(array,character) returns pointer to character in the array
if ( !strchr(charArray,'@') || !strchr(charArray,'.') || strchr(charArray,' ')) {
entryValid = 0;
}
return entryValid;
}
