0

So I'm very new to programming and i have to make a code that asks the user their firs name and last name, and then to create a password with at least 3 characters and one uppercase letter and I'm very lost, my code has many issues and i don't think it makes a whole lot of sense, here it is:

#include <stdio.h>
#include <string.h>

int main()
{
    char name[20], last_name[20];
    printf("Please, enter your name and last name:\n");
    printf("Name: ");
    scanf("%s", name);
    printf("Last name: ");
    scanf("%s", last_name);


    char userInput[64];
    char pass = 0;
    char password[25];
    int i;
    int x;
    size_t length = 0;
    while( pass == 0 ) {

        length = 0;
        pass = 0;

        printf("\nPlease, create a password:\n ");
        fgets(userInput, 63, stdin);
        length = strlen(userInput);

        if( length < 4) {
            printf("The password must have at least 3 characters\n");
            continue;
        }

        scanf(" %s", password);
        for (i = 0; i < 25; i++) { 
        if (isupper(password[i])) { 
            break;
        }
        else if (password[i] == '\0') { 
            printf("\nPlease, enter at least one uppercase letter\n");
            break;
        }
    }
    }

    return 0;
}

the "Please, enter your name and last name" repeats itself the first time it appears and i don't know why, and when the password doesn't have an uppercase it doesn't ask the user to create a new password, how can i fix any of this?

any help is much appreciated

  • Your program doesn't hide users' passwords in the console/terminal, btw. – Dai Jul 24 '21 at 10:04
  • You need to set an upper-bound on `scanf`'s input otherwise users with names longer than 20 characters will cause a buffer-overrun. [You should use `scanf_s` instead of `scanf`](https://stackoverflow.com/questions/21434735/difference-between-scanf-and-scanf-s). – Dai Jul 24 '21 at 10:05
  • 1
    Use `scanf("%19s", name)`, or at least get `scanf()`'s return value `if (scanf(...) == NULL) { /* handle error */ }` to ensure the values were correctly taken and assigned. – Rohan Bari Jul 24 '21 at 10:10
  • Avoid using both `fgets()` and `scanf()` to read user input. Avoid `scanf()` until you know why it is bad. For now, I recommend to read all user input with `fgets()` and see [this](https://stackoverflow.com/q/2693776/2410359). – chux - Reinstate Monica Jul 24 '21 at 10:24
  • @lala lele - It is not credible that _the "Please, enter your name and last name" repeats_, since the `printf` call is not part of a loop or recursion. – Armali Jul 25 '21 at 07:47

0 Answers0