I am trying to figure out where my mistake is. My function is not returning the proper value for x. I am trying to check the password input for digits as a requirement that all passwords contain at least one digit otherwise cout the error message. Any help would be greatly appreciated.
//Austin W.
//Password Checker
#include <iostream>
#include <string>
#include <cstring>
#include <cctype>
usingnamespace std;
int digits( char array[], int);
int main ()
{
int i, x = 0, size;
constint minimum = 6;
char password[99];
cout << "Please enter a password:";
cin >> password;
size = strlen(password);
if (size < minimum)
{
cout << "Passwords must be at least 6 characters long" <<endl;
}
elseif(digits(password, size) > 0)
{
cout << "That is an acceptable password" <<endl;
}
else
{
cout << "Passwords must contain at least one number" <<endl;
}
cin.clear();
cin.ignore(255, '\n');
cin.get();
return 0;
}
int digits(char password[], int size)
{ for (int i = 0, x = 0; i < size; i++)
if (isdigit(password[i]))
{
x++;
return x;
}
}
Inside digits(), you always return immediately after incrementing x. So when you return, x will always be 1. Think about what happens if the password contains no digits; then you'll hit the end of the function without returning anything. Most compilers would give a warning to the tune of "not all control paths return a value" for something like that.
int digits( char array[], int);
int main ()
{
int i, x = 0, size; // "i" is not being used
const int minimum = 6;
char password[99];
cout << "Please enter a password:";
cin >> password;
size = strlen(password);
if (size < minimum)
{
cout << "Passwords must be at least 6 characters long" <<endl;
}
else
if(digits(password, size) > 0)
{
cout << "That is an acceptable password" <<endl;
}
else
{
cout << "Passwords must contain at least one number" <<endl;
}
cin.clear();
cin.ignore(255, '\n');
cin.get();
return 0;
}
int digits(char password[], int size)
{
for (int i = 0, x = 0; i < size; i++)
{
printf( " this is a char # %d check x= %d\n ", i,x );
if (isdigit(password[i]))
{
// x++;
printf( " \n\nThis is a Pleasent char # %d check x= %d\n ", i,x );
return ++x; // inc. x by one first, then rtn()
}
By placing some flags to show what was being done, where & when and what vals were being set, I was able to see that the RTN value was not being set correctly. -
In fact, there was NOT any rtn() value at all !
Fixed this bug -
- ps, left my two PRINTF() statements in, so you could verify.
@Zhuge & Incis B: Thank you both very much for your help. Sometimes it makes a big difference getting a second set of eyes on a problem. All is working well now.