0

I'm a beginner programmer and a have this problem that I'm unable to solve. My assignment is to create a password checking program, which woud take unlimited amount of passwords from stdin (in a file and read every line as a separate password) and test them on four different levels of security. We can't use string.h, ctype.h, malloc, free...

I'm stuck at the first level, which is "test that password includes both lowercase and uppercase letters. I was able to check if it contains at least one of those, or if it is only comprised of combinations of two, with the code below, but I'm lost beyond that. Please, help.

while (string[i] != '\0')
{
    if (isChar_abc(string[i]) == false)
    {
        if (isChar_ABC(string[i]) == true)
        {
            i++;
        }
        else if (isChar_ABC(string[i]) == false)
        {
            printf("Error, end code\n");
            return 0;
        }
    }
    else if (isChar_ABC(string[i]) == false)
    {
        if (isChar_abc(string[i]) == true)
        {
            i++;
        }
        else if (isChar_abc(string[i]) == false)
        {
            printf("Error, end code\n");
            return 0;
        }
    }
}
  • 2
    I'd use two counters, one for lower and one for upper. As you iterate through the string increment lower for lowercase characters and upper for uppercase characters. If at any point they are both non zero then your string has both. If you get to the end and either or both are 0 then you don't. – Retired Ninja Oct 24 '21 at 11:47
  • the posted code is only a fragment. It does not compile! Please post a [mcve] so we can reproduce the problem and help you debug it. – user3629249 Oct 24 '21 at 17:56

2 Answers2

0

to check if it contains both iterate over the string and set flags if each is found

char containsboth(char* str) {

    int   i;
    char  lower = false, upper = false;

    for (int i = 0; str[i] != '\0'; i++) {
        lower = lower || (str[i] >= 'a' && str[i] <= 'z');
        upper = upper || (str[i] >= 'A' && str[i] <= 'Z');

        if (lower && upper) break;
    }

    return (lower && upper);

}

check: C programming: How to check whether the input string contains combination of uppercase and lowercase

arp5
  • 151
  • 9
0

OP's code uses i++; to count both upper and lower case letters.

Supposedly a final if (i >= 2 /* or 1 */) occurs, yet that does not detect if both upper and lower occurred.

Better to use 2 different i

upper_i++;
...
lower_i++;

Sample code simplification:

int contains_upper_and_lower(const char *string) {
  int contains_upper = 0;
  int contains_lower = 0;

  int i;
  while (string[i]) {
    if (isChar_ABC(string[i])) contains_upper = 1;
    else if (isChar_abc(string[i])) contains_lower = 1;
    i++;
  }
  return contains_upper && contains_lower;
}
chux - Reinstate Monica
  • 127,356
  • 13
  • 118
  • 231