Checking for code matching in a vector within a struct in C

1

Next, I've created a struct

 struct eventos
{
    int codigo;
    char data[11];
    char atracao[50];
    int ingresso;
    float valoring;
};

And so, I created a vector that way

struct eventos ficha[5];

My goal is to check inside a function called query (), if a user supplied code matches the code of an event already registered previously (In this program there is the possibility of registering an event and one of the categories of the record is the event code), and then, after that check, I display the event data through another function named display (). I created the query () function as follows:

void consulta()
{
    printf("Digite o codigo do evento que deseja consultar\n ");
    scanf("%d", &code);
    for(h=0;h<2;h++)
        {
            if(code == ficha[h].codigo)
            {
                exibir();
                system("pause");
                system("cls"); 
            }

                else 
                {
                    printf("Evento nao cadastrado\n ");
                    system("pause");
                    system("cls"); 
                }
        }
}

However, a problem persists every time I search for a code, if it is in the first positions of the vector, the event data is displayed, followed by, for example, two messages of "Event not registered" . Similarly, if the code is in the last positions, "Event not registered" is displayed first, to finally display the event information corresponding to the inserted code. I would like to know how I get the program to break the loop as soon as it finds a valid code and displays the event data. I have tried to use the "break;" function, but somehow it works for the first test, but when registering two events, I succeed by referring to the first one and the second one is an unregistered event.

If you can help me out, I'll be very grateful!

    
asked by anonymous 24.09.2017 / 21:33

1 answer

0

I made some modifications to your function see:

void consultar(){
    printf("Digite o codigo do evento que deseja consultar\n ");
    int code,posicao,achou=0;
    scanf("%d", &code);
    for(int h=0;h<2;h++){
        if(code == ficha[h].codigo){
            achou=1;
            posicao=h;
        }
    }

    if(achou == 1){
        printf("%d",ficha[posicao].codigo); 
        printf("Evento cadastrado\n ");                
        system("pause");
    }else{
        printf("Evento nao cadastrado\n ");
        system("pause");            
    } 
}

The function now works as follows, if it finds it it adds +1 to a variable and another one saves the position.

If the variable found = 0, it does not have this code in the vector, if the variable = 1 there is this code in the vector.

Your error is:

You are doing the logical test at each position of the vector, so if this position has the code you are looking for, it will give true if it is not going to give false.

    
24.09.2017 / 22:01