Matheus Dutra Matheus Dutra - 3 months ago 10
C Question

Password strength detector in C doesn't work

The password needs a letter and a number. Here's the code:

#include <ctype.h>
int main()
{
char password;

printf("Please enter a password.\n");
scanf("%c", &password);

if ((isalpha (password) && isdigit(password))){
printf("Your password is strong!\n");
} else {
printf("Your password is weak!");
}
return 0;
}


However, when I compile it, it always prints "Your password is weak" even when I type in both characters and numbers. What's wrong?

Answer

You're only reading a single character from the user:

char password;

printf("Please enter a password.\n");
scanf("%c", &password);

Since that single character cannot be both a digit and a letter, the first conditional always fails.

You need to read the entire string from the user. Then, use a loop to iterate over every character in the string to check the presence of the various types of characters you require. The functions from ctype.h take a single character, not a string -- it would fail to compile if you tried to pass them a char array or pointer anyway.