Search code examples
cpassword-checker

Password input always returns "not eligible"


I'm learning C right now.

I have been working on a program that will check user's input (password eligibility). In order for password to be considered as eligible and considerably strong, it needs to have at least of one from the list of following items:

  • Uppercase letter;
  • '$' sign;
  • Alphanumerical character;

In my program I have created three integer variables that will keep count of upper mentioned requirements.

Unfortunately, whenever I input the "correct" version of password, the program keeps printing that the password is not eligible.

Please give me a clue, where I might be wrong.

//challenge: 
//build a program that checks when user enters a password for an uppercase letter, a number, and a dollar sign.
//if it does output that password is good to go.

int main()
{
    char passwordInput[50];
    int alphaNumericCount = 0;
    int upperCharacterCount = 0;
    int dollarCount = 0;

    printf("Enter you password:\n");
    scanf(" %s", passwordInput);

    //int charactersAmount = strlen(tunaString);

    for (int i = 0; i < 49; i++){
        //tunaString[i]

        if( isalpha(passwordInput[i]) ) {
            alphaNumericCount++;
            //continue;
        }else if( isupper(passwordInput[i]) ) {
            upperCharacterCount++;
            //continue;
        }else if( passwordInput[i] == '$' ) {
            dollarCount++;
            //continue;
        }
    }

    if( (dollarCount == 0) || (upperCharacterCount == 0) || (alphaNumericCount == 0) ){
        printf("Your entered password is bad. Work on it!\n");
    }else{
        printf("Your entered password is good!\n");
    }

    return 0;
}

Solution

  • The isalpha function returns true if the character is either upper case or lower case. You do that before the condition that calls isupper. Since an upper case character will satisfy the first condition, the second condition will never evaluate to true.

    Since being upper case is a subset of being alphanumeric, you need to revise your requirements. If instead you want to check for (for example):

    • upper case
    • numeric
    • "$"

    Then you would have one condition use isupper, one use isdigit and one compare with '$'.

    Also, you loop through all elements of the passwordInput array, even if they're not all populated. Instead of testing i<49, use i<strlen(passwordInput).