Search code examples
ccharacter-arrays

Why does this code to validate passwords always reject the input?


I tried to write a program that reads a password and accepts it only if it contains a dollar sign, an upper-case letter, and a digit. Here's the code:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main()
{
    int i=0;
    char chr;
    int dollar,upperC,number=0;
    char password[100];

    printf("enter the password\n\n");
    scanf("%s",password);

    for( i=0;i<=99;i++){
        chr=password;

        if(chr=='$'){
            dollar=1;
        }
        if(isdigit(chr)){
            number=1;
        }
        if(isalpha(chr)){
            if(isupper(chr)){
                upperC=1;
            }
        }
        if(dollar==1&&number==1&&upperC==1){
            printf("your password has accepted");
        }else{
            printf("your password has not accepted");
        }
        return 0;
    }
}

However, the program seems to reject all passwords, even ones where the conditions are fulfilled. Can someone help me see why this is?


Solution

  • There are several issues in this program; here are a few. As a note, most of these would probably be caught by a C compiler with the warning level cranked all the way up to maximum, so I recommend turning on warnings and making sure your programs compile cleanly before running them. With that said, here are some specific errors in the program:

    When you write

    int dollar,upperC,number=0;
    

    C interprets this as equivalent to

    int dollar;
    int upperC;
    int number = 0;
    

    As you can see, dollar and upperC are uninitialized, so their values are undefined (but typically not zero). Try changing your code to set these to zero by writing

    int dollar = 0, upperC = 0, number = 0;
    

    Or, even better, include <stdbool.h> and write

    bool dollar = false, upperC = false, number = false;
    

    Additionally, note that your if/else test for the password is inside the for loop, meaning that you will test whether all character types are present without looking at all the possible characters in the input. To fix this, move your if/else outside of the loop.

    This line is also incorrect:

    chr=password;
    

    This will not set chr to the next character of password. I think you meant

    chr = password[i];
    

    Finally, make sure that you don't loop up to index 99, inclusive. That might read past the end of the string. Instead, loop only up to the number of logical characters inside the string.

    Hope this helps!