Retry user and password attempts

8

I wanted a program that checks the user and password, if it was correct to display a message, if it repeated the check and if the attempts were equal to 3, it showed the limit message of attempts reached.

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

int main()
{
    char user[20];
    int senha, contador = 0;

    printf("Entre com o usuario: ");
    gets(user);

    printf("Entre com a senha: ");
    scanf("%d", &senha);

    while((strcmp(user, "leonardo") == 0) && senha == 123) {
    if(1) {

        printf("\nAcesso concedido.\n");
        break;

     } else {
       contador = contador + 1;
       gets(user);
       scanf("%d", &senha);

       } if(contador == 3) {
       printf("Limite de tentativas alcancadas.\n");
       }
    }

    printf("Fim.\n");
    return 0;
}

I'm having difficulty with loops .

    
asked by anonymous 02.05.2016 / 13:32

1 answer

7

There is a lot of code repetition in this. Then you get confused and start having some logic problems. It would be better to do all checking inside the loop.

Note that the count of attempts should always occur, not conditionally. It is much simpler to understand the flow when the values of the variables reflect what they actually represent. If an attempt has been made, the variable must count 1. If you have made one more attempt, you must add it. And check if you've reached the number of attempts allowed.

Obviously it would be interesting to do something beyond this, but it's an initial foundation that works:

char user[20];
int senha, contador = 0;
do {
    printf("Entre com o usuario: ");
    gets(user);
    printf("Entre com a senha: ");
    scanf("%d", &senha);
    // aqui as credenciais estão corretas
    if (!strcmp(user, "leonardo") && senha == 123) {
        printf("\nAcesso concedido.\n");
        break;
    }
    contador++;
} while (contador < 3);
if (contador == 3) {
    printf("Limite de tentativas alcancadas.\n");
}
printf("Fim.\n");
return 0;

See running on ideone .

Testing over limit .

I made a change because it is not recommended to use gets() and some compilers can not use it in their default form (I can not configure it in ideone).

    
02.05.2016 / 14:07