Vector reading in C is wrong

4
struct cadastro{
int codigo;
char nome[200];
char cpf[11];
char rg[10];
char tel[12];
char end[100];

}cadastro;//struct do tipo cadastro.

struct cadastro cd[max];//vetor da funcao cadastro de cliente

I have set up a menu, with do - while , and getting the parameter and using switch redirects the modules accordingly.

What should happen, I call the function vender()

void vender()
{
int cod,client;
char resp;

system("cls");

printf("------------------------------------------\n");
printf("------------Seja bem vindo----------------\n");
printf("------------------------------------------\n");
printf("Por favor entre com o codigo de cliente:  \n");
scanf("%d",&cod);

system("cls");

for(int i = 0; i < max; i++)
{
    if(cd[i].codigo == cod)
    {
        client = i;
    }
    else
    {
        if(cd[i].codigo != cod)
        {
            printf("Usuario nao cadastrado, deseja cadastrar?[s/n]: ");
            scanf("%s",&resp);

            if(resp == 's')
            {
                cad_cliente();
            }
            else
            {
                menu();
            }
        }
    }
}

system("cls");

printf("-------------------------------------------\n");
printf("Cod: %d\n",cd[client].codigo);
printf("Nome: %s\n",cd[client].nome);
printf("Tel: %s\n",cd[client].tel);
printf("-------------------------------------------\n");
}

And I check if there is a user registered, not having, I go and register, I go back and I call the function vender() , I consult the customer code that I registered and nothing happens ...

Did I do something wrong in this code snippet?

Full Code .

    
asked by anonymous 09.05.2016 / 00:08

1 answer

4

At some points it already does better than some beginners. But there are still some basic mistakes. It has a large amount of small and big bugs in what it is doing. I will only solve the most serious in the presented section:

void vender() {
    system("cls");
    printf("------------------------------------------\n");
    printf("------------Seja bem vindo----------------\n");
    printf("------------------------------------------\n");
    printf("Por favor entre com o codigo de cliente:  \n");
    int cod;
    scanf("%d", &cod);
    system("cls");
    int client = -1;
    for (int i = 0; i < max; i++) {
        if (cd[i].codigo == cod) {
            client = i;
            break; //se achou não precisa continuar procurando
        }
    }
    if (client == -1) { //se ainda é -1 não acho a posição do cliente, então não existe
        printf("Usuario nao cadastrado, deseja cadastrar?[s/n]: ");
        char resp;
        scanf("%s", &resp);
        if (resp == 's') {
            cad_cliente();
        } else {
            return;
        }
    }
    system("cls");
    printf("-------------------------------------------\n");
    printf("Cod: %d\n", cd[client].codigo);
    printf("Nome: %s\n", cd[client].nome);
    printf("Tel: %s\n", cd[client].tel);
    printf("-------------------------------------------\n");
}

I'll tell you something that will not do for most people, but I think your case will be different. Always try to organize the code well (yours is above average), give meaningful names to variables, and keep a clean standard. The only further recommendation I would make is to separate the parentheses from if , for , while , since they are not functions and may look strange.

Maybe you did not know else if which would simplify your code a bit. It executes that block if it meets that condition. But in the specific case the else if would not be necessary since the condition of this second if would be the opposite of the first. Then just a else . The else is just to execute a block with condition opposite to if . I think you have not yet understood the function of if .

But in the specific case there was another problem of logic. He did not do what he imagined. What he did is that if the chosen code was not the first one in the registry, he considered that the client was not registered. But it could be in the next codes. It has to analyze everything and only if it does not find in any is that it should decide that the user is not registered. I made a change. Nor will I explain in detail, I do not think you're in the right place for this.

There was a call from menu() . This is not only not necessary since if you allow yourself to continue, the code will return to it. But calling a code from which that function was called will create an unwanted cycle and create a potential of stack overflow (I will not go into detail here, it is a more advanced subject, for now be careful not to create call cycles). If it is to terminate and return to the calling function, just use a return , do not call it again.

I'm concerned about calling cad_cliente() there as well. It might not be a problem, but it is wrong and will cause problems. Note that in all functions you are using this call to menu . You need to understand the return of roles. You should call something, this something run and quit, it's a back and forth:

função chamadora <-> função chamada

Your code does:

    função chamadora -> função chamada -> função chamadora

When you finish the second call function, it will return to the called function, which will then return to the calling function. I guarantee this is not what you want.

In the first example when the called function terminates, it does not call anything, it returns to the caller, that's how it should be. Function calls should work as stacks instead of as cycles .

I also left the declaration of resp closer to where it is used. I did msmo with the other variables, but keeping the same scope. The technique of declaring everything you will use before is outdated. And the code itself is already more modern in the use of i .

After you improve and still have questions, you can post another question to help us more.

I'm not going to look at all the code but looking at the customer registration function I saw another cycle problem. There's a recursion there (it's something you'll learn in the future). Recursion can be helpful, but in specific cases and when you know what you are doing, it can not be used in any case and can not be by accident. If you want to do another register you should control this with a loop, as you did correctly in menu() (although case 8 is required to have a exit(1) , you can exit by normal paths ending the loop.You can even work your way, but you will be learning wrong for the initial goal.

I realize that I still do not understand the operation of loops and especially how a function works, especially how it closes. Do not go forward without having full control of it.

You should avoid global variables like they did, but it might be early to teach the right way to do this. There are several things that should be done differently but you can not explain it here and I do not know if I should do it already, you will notice over time as the problems of some things made in this code evolve.

I'm not even going to talk about fflsush(stdin) and gets() . This is a mistake, but if it is working, go for it for a while, then learn to do it right.

My conclusion is that you are trying to make code too complex for your current ability to understand algorithms. You should go back one step and understand each individual construction in its fullness before attempting to make more complex codes uniting the various resources. If you skip steps you will have a lot of difficulty and you will probably learn wrong what will complicate you forever.

    
09.05.2016 / 01:28