In: Computer Science
Create a C++ program which will prompt the user to enter a password continually until the password passes the following tests.
Password is 6 chars long
Password has at least 1 number
If the input does not match the tests, it will input a specific error message. "Pass must be 6 chars long."
If the input is allowed, print a message saying "Correct Password Criteria."
C++ Program :
#include <iostream>
using namespace std;
bool validPassword(string s) // ensures that the password has atleast 1 number in it
{
int count =0;
for(int i=0; i<s.length(); i++) // iterate through all characters in string
{
if(s[i]>='0' && s[i]<='9') // check if characters are between 0 to 9 (contain digits)
{
count++; // if it contains digits increment count
}
}
if(count>0) // return true only when there is atleast one number in password
{
return true;
}
else
{
return false;
}
}
int main()
{
string password;
while(1) // infinite loop
{
cout << "Please enter a password : "; // ask for password from user
cin >> password;
if((password.length() == 6) && validPassword(password)) // check if password is in correct criteria
{
cout << "Correct Password Criteria."<<"\n"; // end the loop if we get correct criteria
break;
}
else // print a error message saying specific error
{
if(password.length() != 6)
{
cout << "Password must be 6 chars long.\n\n";
}
else
{
cout << "Password must have atleast 1 number.\n\n";
}
}
}
return 0;
}
Screenshots :