Repeat user and password typing attempts

Asked

Viewed 1,772 times

8

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

#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 trouble with the loops.

1 answer

7


There is a lot of code repetition in it. Then it gets confused and starts to have some logic problems. It would be better to do every check inside the loop.

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

Obviously it would be interesting to do something beyond this, but it is an initial basis 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");

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Test exceeding the limit.

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

  • When the program reaches 3 attempts it will end with both while and if

  • Yeah, I had thrown the counter to the end, then moved the if to the wrong location. I edited and now it’s ok.

  • Only a small repair, attempts are 3, but the counter starts at 0, which makes the while and the check are 2

  • Yeah, it’s only 2 and still doesn’t show the message.

  • That’s right. Now.

  • Yes, the counter starts at 0, after all when it starts zero attempts form made. The while repeat until three attempts are reached. Actually the operator could not be <=. Tidy.

  • Goes from 0 to 2, is 3 attempts.

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.