How to use if inside the for, without the outside if appearing?

printf("\nDigite o usuario que deseja pesquisa, pela Matricula: \n");
gets(strL);
busca=atoi(strL);
for(i=0; i<quant; i++) {
    if(busca==dados[i].matricula) {
        printf("Aluno: %d\n",i);
        printf("Nome: %s\n",dados[i].nome);
        printf("CPF: %s\n",dados[i].cpf);
        printf("Matricula: %d\n",dados[i].matricula);
        printf("Idade: %d\n",dados[i].idade);
        printf("\n-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-\n");
    }
}
    if(busca!=dados[i].matricula) {
       printf("pesquisa invalida, tente novamente! \n");
    }

The code compile normally. The problem is that the first if is for when it is equal and the second is for when for different and in this case, when I compile both the if inside the for and the outside of the for, and executed, being that only one is true.

printf ("search invalidity invalidity, try again");

Author: Maniero, 2020-04-04

1 answers

The best way is to use a function since without it you would have to create a flag which is gambiarra, and the function better isolates what each thing is.

You want it to show the user if you find it and then terminate it with nothing else, or else if it searched all users and did not find a data you want a message to indicate this, so:

void mostraUsuario(int codigo) {
    for (int i = 0; i < quant; i++) {
        if (dados[i].matricula == codigo) {
            printf("Aluno: %d\n",i);
            printf("Nome: %s\n",dados[i].nome);
            printf("CPF: %s\n",dados[i].cpf);
            printf("Matricula: %d\n",dados[i].matricula);
            printf("Idade: %d\n",dados[i].idade);
            printf("\n-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-\n");
            return;
        }
        printf("pesquisa invalida, tente novamente! \n");
        return;
    }
}

I put on GitHub for future reference.

Has other problems in the code, even without seeing the whole it, but it will work in an exercise, so I will not try to solve.

 1
Author: Maniero, 2020-04-06 11:55:55