C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1
if ((hasDigit) && (hasUpper) && (hasLower))
{
printf("\n\nExcellent work, %s,\n", user);
printf("Your password has upper and lowercase ");
printf("letters and a number.");
} else
{
printf("\n\nYou should consider a new password, %s,\n",
user);
printf("One that uses upper and lowercase letters ");
printf("and a number.");
}
return(0);
}

Anyone creating a password these days gets a lecture about the need for a variety of letters, numbers,
and, in some cases, characters in their password to make it difficult for hackers to crack their code.
This program uses the functions listed in this chapter to check that a password has each of the three
types of characters in an entered password by looping through the password character by character
and testing each of the three types. If a specific character is one of those three types, a variable flag is
set to 1 (TRUE in C parlance), and then the loop moves on.


In the case of the first two tests, after the variable flag (hasDigit or hasUpper) is set to 1 , a
continue statement starts the next version of the loop—after the character has been determined to
be a digit, there is no need to run the next two tests (after all, it can’t be more than one category,
right?), so for efficiency’s sake, skipping the subsequent tests makes sense. The last if code section
does not need a continue statement because it is already at the end of the loop.


After all the characters in the password string have been tested, an if statement checks whether all
three conditions were met. If so, it prints a congratulatory message. If not, it prints a different
message.


Tip

Some passwords today also ask for at least one non-letter, non-number character (such
as $, !, *, &, and so on). You could further refine this code to check for those by
putting an else at the end of the final islower test. After all, if a character fails the
first three tests, then it fits in this last category.

Case-Changing Functions


C has two important character-changing functions (also called character-mapping functions) that
return their arguments changed a bit. Unlike isupper() and islower(), which only test
character values and return a true or false result of the test, toupper() and tolower()
return their arguments converted to a different case. toupper() returns its parentheses argument as
uppercase. tolower() returns its parentheses argument as lowercase.

Free download pdf