![]()
Source for week 3 content, "reading user input"
You should be able to cut and paste the text from this page into your C editor.
-------------------------------------- cut after this line -----------------------------------------------------------
#include <string.h>
#include <stdio.h>
#include <ctype.h>
int getEmail(char * userEmail);
int getFirstName(char * firstName);
int getLastName(char * lastName);
int getPhoneNumber(char * userPhone);
void main()
{
char userEmail[80];
char firstName[80];
char lastName[80];
char userPhone[80];
int nameValid;
do {
nameValid = getFirstName(firstName);
if (nameValid == 1) {
printf("You entered: %s, a good name\n",firstName);
}
else {
printf("You entered an invalid name, try again\n");
}
}
while (nameValid == 0);
}
int getFirstName(char * charArray)
{
int entryValid = 1; // presume entry is valid until we disprove it
int entryLength,i;
printf("Enter the first name: ");
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;
}

