C++ program that asks for a password and then verifies that it meets the stated criteria
Password Verifier
Imagine you are developing a software package that requires users to enter their own
passwords. Your software requires that users’ passwords meet the following criteria:
• The password should be at least six characters long.
• The password should contain at least one uppercase and at least one lowercase
letter.
• The password should have at least one digit.
Write a C++ program that asks for a password and then verifies that it meets the stated criteria.
If it doesn’t, the program should display a message telling the user why.
Answer:
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 // Password Verifier
#
include
<iostream>
#
include
<string>
#
include
<cctype>
using
namespace
std;
// Function prototype
bool validPassword(char []);
int main()
{
// Constant for the array size
const
int SIZE = 80;
// Array to hold a password
char cstring[SIZE];
// Get a password from the user.
cout <<
"Enter a password: "
;
cin.getline(cstring, SIZE);
// Tell the user whether the password
// is valid or not.
if
(!validPassword(cstring))
cout <<
"The password is not valid.\n"
;
else
cout <<
"The password is valid.\n"
;
return
0;
}
//***********************************************
// Function validPassword *
// This function returns true if the password *
// stored in str is valid. Otherwise it returns *
// false. *
//***********************************************
bool validPassword(char str[])
{
// The following flag variables will indicate
// whether the password has an uppercase letter,
// a lowercase letter, and a digit.
bool hasUpper = false,
hasLower = false,
hasDigit = false;
// If the password is less than six characters
// we know immediately that it is not valid,
// so go ahead and return.
if
(
strlen
(str) < 6)
{
cout <<
"The password must be 6 or more "
<<
"characters long.\n"
;
return
false;
}
// Test each character in the password.
while
(*str != 0)
{
if
(isupper(*str))
hasUpper = true;
// Uppercase
else
if
(islower(*str))
hasLower = true;
// Lowercase
else
if
(isdigit(*str))
hasDigit = true;
// Digit
// Go to the next character.
str++;
}
// If the password does not have an uppercase
// character AND a lowercase character AND a
// digit, it isn't valid.
if
(!hasUpper || !hasLower || !hasDigit)
{
cout <<
"The password must have:\n"
;
cout <<
"\tat least one uppercase character,\n"
;
cout <<
"\tat least one lowercase character, and\n"
;
cout <<
"\tat least one numeric digit\n"
;
return
false;
}
// If we made it to this point, the password is valid.
return
true;
}
Leave a reply