In: Computer Science
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 be at least one uppercase and at least one lowercase letter. The password should have at least one digit. Write a program that asks for a password then verifies that it meets the stated criteria. If it doesn't, the program should display a message telling the user why.
C++ Program:
#include <iostream>
using namespace std;
//Declaring constants
const int SIZE = 80;
const int MIN = 6;
//Function Prototype
bool isValid(char pwd[]);
//Main function
int main()
{
//Character array that stores password
char password[SIZE];
//Loop till user enters a valid password
while(true)
{
//Displaying password requirements
cout << "\n\n Password requirements: \n - The password should
be at least 6 characters long \n - The password should contain at
least one uppercase ";
cout << "\n - and one lowercase letter. \n - The password
should have at least one digit. \n";
//Reading password
cout << "\n Enter a password: ";
cin >> password;
//Validating password
if(isValid(password))
{
//If valid password
cout << "\n The password is valid \n";
break;
}
else
{
//If invalid password
cout << "\n The password was invalid \n";
}
}
cout << "\n\n";
return 0;
}
//Function Definition
bool isValid(char *password)
{
int i, len;
bool hasLower=false, hasUpper=false, hasDigit=false, hasLength;
//Finding length
len = strlen(password);
//Finding length
if(len >= MIN)
{
//Set length to true
hasLength = true;
//Iterating over string
for(i=0; i<len; i++)
{
//Testing for upper
if(isupper(password[i]) && hasUpper == false)
{
hasUpper = true;
}
//Testing for lower
if(islower(password[i]) && hasLower == false)
{
hasLower = true;
}
//Testing for digit
if(isdigit(password[i]) && hasDigit == false)
{
hasDigit = true;
}
}
}
else
{
cout << "\nPassword is not of minimum six characters
long...\n";
//If length is not sufficient
return false;
}
//Checking one by one
if(hasDigit==false)
{
cout << "\nPassword doesn't contain digit....\n";
}
if(hasLower==false)
{
cout << "\nPassword doesn't contain lowercase
letter....\n";
}
if(hasUpper==false)
{
cout << "\nPassword doesn't contain uppercase
letter....\n";
}
//Return status
return (hasDigit && hasLower && hasUpper);
}
___________________________________________________________________________________________
Sample Run: