Exercise 10.1: C-String
Here is the problem specification:
Write a program to determine whether or not an entered password is valid. Valid passwords consist of 10 characters, 4 of which must be letters and the other 6 digits. The letters and digits can be arranged in any order. Only lowercase letters are allowed for valid passwords.
Hints: use islower, isalpha, isdigit, and strlen.
Sample Run
Enter a password consisting of exactly 4 lower case letters and 6 digits:
asb12
Invalid password. Please enter a password with exactly 4 lower case letters and 6 digits
For example, 1234abcd56 is valid. Please enter again:
123sbdf
Invalid password. Please enter a password with exactly 4 lower case letters and 6 digits
For example, 1234abcd56 is valid. Please enter again:
abcd123456
The number of lower case letters in the password is 4
The number of digits in the password is 6
============
Sample Run again.
Enter a password consisting of exactly 4 lower case letters and 6 digits:
123anbd456
The number of lower case letters in the password is 4
The number of digits in the password is 6
#include <iostream>
#include <cctype>
#include <stdio.h>
#include <string.h>
using namespace std;
//function prototypes
bool testPassWord(char[]);
int main()
{
char passWord[20];
cout << "Enter a password consisting of exactly 4 lower case letters and 6
digits:" << endl;
do {
cin.getline(passWord, 20);
if (testPassWord(passWord)) {
cout << "The number of lower case letters in the password is " <<
4 << endl;
cout << "The number of digits in the password is " << 6 << endl;
}
else
{
cout << "Invalid password. Please enter a password with exactly 4
lower case letters and 6 digits" << endl;
cout << "For example, 1234abcd56 is valid. Please enter again:"
<< endl;
}
} while (testPassWord(passWord) == false);
return 0;
}
bool testPassWord(char password[20])
{
int letters = 0, digits = 0;
for (int i = 0; i < strlen(password); i++) {
if (isalpha(password[i]) && islower(password[i])) {
letters++;
}
else if (isdigit(password[i])) {
digits++;
}
}