My program won't read every character in a string

I need the code below to check each character to see if it's a capital letter, digit, or space. The program will only check if the first character is a capital letter or digit. How can I resolve my issues with the code?
My issues with the code:
- It will only read the first character of the string.
- It will not check for spaces.

#include <iostream>
#include <cctype>
#include <string>
#include <cstdlib>
using namespace std;
bool test(char, int);
int main()
{
int size;
string password;
cout << "Please enter the size of the password." << endl;
cin >> size;
if (size < 8)
{
cout << "You must have a minimum of eight characters in your password." << endl;
return 0;
}
cout << "Please enter a password." << endl;
cin >> password;
if (test(password, size))
{
cout << "This password meets the essential criteria." << endl;
}
}
bool test(char password, int size)
{
int count;
for (count = 1; count < size; count++)
{
if (!isupper(password))
{
cout << "You need at least one upper case letter in the password." << endl;
return false;
}
if (!isdigit(password))
{
cout << "You need at least one digit in the password." << endl;
return false;
}
if (!isspace(password))
{
cout << "You may not have any spaces in the password." << endl;
return false;
}
}
return true;
}
cin >> password; operator>> does formatted input. It skips leading whitespace characters and then reads data until it encounters another whitespace character. If you intend to use space in your password, you need to use unformatted input. getline might help you here.
Your test() function tests a single character. You need to test the whole string. I suggest you do it like this:
- create local variables for the number of uppercase characters, digits, and spaces.
- go through the password counting up the above.
- Check the three counters, If any are zero then say that the password is bad.

One of the nice things about this approach is that, of the password fails for multiple reasons you can print the all.
Topic archived. No new replies allowed.