Vector reading in C is wrong

Asked

Viewed 105 times

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 put together a menu, with do - while, and with obtaining the parameter and using switch redirect to the agreement modules.

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 registered user, not having, I go and register, I go back and call the function vender(), I consult the client code I registered and nothing happens...

I did something wrong in that code snippet?

Complete code.

  • Did the answer solve your problem? Do you think you can accept it? If you don’t know how you do it, check out [tour]. This would help a lot to indicate that the solution was useful to you and to give an indication that there was a satisfactory solution. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

1 answer

5

At some points it already does better than some beginners. But it still has some basic mistakes. There are a lot of small and big mistakes in what you are doing. I will just solve the most serious in the presented excerpt:

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 put in the Github for future reference.

Let me tell you something that doesn’t usually work out for most people. Always try to organize the code well (yours is above average), give meaningful names to variables and keep a clean pattern. The only other recommendation I would make is to separate the parentheses from the if, for, while, since they are not functions and can get strange.

else if

Maybe you didn’t know the else if which would slightly simplify your code. It executes that block if it meets that condition. But in the specific case the else if nor would it be necessary since the condition of this second if would be the opposite of the first. Then just one else. The else is just to run a block with condition opposite to the if. I don’t think you understand 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 was that if the code chosen was not the first one on his record, he considered that the client was not registered. But it could be in the next codes. You have to analyze everything and only if you do not find in any it is that you should decide that the user is not registered. I made a change. I’m not even going to explain in detail, I don’t think it’s in the right place for this.

Accidental recursion

There was a call from menu(). Not only is this not necessary since if it continues, the code will return to it. But calling a code from which that function was called will create an unwanted cycle that creates a potential for pile burst (I will not go into detail here, it is a more advanced subject, for now try not to create call cycles). If it is to close and return to the calling function, just use a return, don’t call her again.

I’m worried about the call from cad_cliente() there too. 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 functions. You should call something, this something run and end, it’s a back and forth:

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

Your code makes:

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

When the calling function finishes in second place, it will return to the calling function, which will then return to the calling function. I assure you this is not what you wish.

In the first example when the function called closes, it calls nothing, it goes back to who called, that’s how it should be. Function calls should function as batteries and not as cycles.

I’m not going to look at all the code, but looking at the customer registration function, I saw another cycle problem. Ali has a recursion (it’s something he’ll learn in the future). Recursion may be useful, but in specific cases and when you know what you’re doing, it can’t be used in any case and it can’t be by accident. If you want to make another registration you should control this with a loop, as you did correctly in menu() (although the case 8 it is necessary to have a exit(1), can go out in normal ways by finishing the loop. It may even work your way, but you will be learning wrong by the initial goal.

I realize that you still don’t understand how ties work and especially how a function works, especially how it is closed. Don’t go forward without having complete mastery of it.

Organizing

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

I should avoid global variables as it happened, but maybe it’s too early to teach the right way to do this. There are several things that should be done differently, but there is no way to explain here and I don’t know if I should do it now, you will notice over time as the problems of some things done in this code evolve.

I’m not even gonna talk about fflsush(stdin) and of gets(). This is a mistake, but if it is working, it will so for now, later learn to do the right.

After you get better and still have questions you can post on another question to help more.

Completion

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

  • Good evening, bigown first, thank you very much for your help, and I agree on the programming errors, even as I said I learned from 0 to what I "know" in 1 week going through several difficulties and with little education,what happens is that I am in a class ahead of my knowledge, and this "work" is ahead of my knowledge.

Browser other questions tagged

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