When inserting into a vector always overrides the previously inserted value

Asked

Viewed 91 times

-1

In my code when adding a contact (X), and see the contact list, I have contact X, however when adding another contact (Y), and go see the list, the contact Y replaces the X, how can I add several in the vector?

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h> 
/*--------------------------------------ESTRUTURA DA AGENDA------------------------------------------------------*/
 struct Pessoa {
    char nome[100], email [100], rua[100], bairro[100], cidade[100], estado[100], pais[100], numero[4], complemento[10], cep[8], telefone[30], observacao[200];
    int dia, mes, ano;
} Agenda[5]; /* VETOR AGENDA PARA 3 PESSOAS POR QUESTÕES DE SIMPLIFICAÇÃO. OS OUTROS 2 ESPAÇOS SÃO PARA O AUX. */

/*--------------------------------FUNÇÕES (SÃO CHAMADAS PELO MENU)----------------------------------------------*/
void BuscarNome (void);
void BuscarMes (void);
void BuscarMesDia (void);
void InserirContato (void);
void RemoverContato (void);
void AgendaCompleta (void);
int NomeNulo(char *s);

main() {
    int i,j,result, cont=1;
    char escolha;
    /* --------MENU PRINCIPAL DE OPÇÕES----------*/
    menu: 
    printf ("\n");
    printf ("*******************AGENDA PESSOAL*******************\n");
    printf ("*                                                  *\n");
    printf ("*  [1] Buscar contato por nome.                    *\n");
    printf ("*  [2] Buscar contato por mes de aniversario.      *\n");
    printf ("*  [3] Buscar contato por mes e dia de aniversario.*\n");
    printf ("*  [4] Adicionar um contato a agenda.              *\n");
    printf ("*  [5] Remover um contato da agenda.               *\n");
    printf ("*  [6] Mostrar todos os contatos registrados.      *\n");
    printf ("*                                                  *\n");
    printf ("****************************************************\n");

    printf ("Escolha uma opcao: "); scanf("%d", &escolha);

    switch (escolha) {
        case 1 :
            system ("cls");
            BuscarNome();
            goto menu;
            break;

        case 2 :
            system ("cls");
            BuscarMes();
            goto menu;
            break;

        case 3 :
            system ("cls");
            BuscarMesDia();
            goto menu;
            break;

        case 4 :
            system ("cls");
            InserirContato();
            sleep (2);
            system ("cls");
            goto menu;
            break;

        case 5 :
            system ("cls");
            RemoverContato();
            goto menu;
            break;

        case 6 :
            system ("cls");
            AgendaCompleta();


            goto menu;
            break;

        default :
            system ("cls");
            printf ("\n");
            printf ("               Digite uma opcao valida\n");
            sleep (2);
            goto menu;
            break;

    }

    system("pause");
}

void BuscarNome () {
    printf ("Vc buscou um contato pelo nome!");
}

void BuscarMes () {
    printf ("Vc buscou um contato pelo mes de aniversario!");
} 

void BuscarMesDia () {
    printf ("Vc buscou um contato pelo mes e dia de aniversario!");
} 

void InserirContato () {
    int cont=1;
    printf ("Adicionar um contato:\n");
    printf ("Nome: ");
    scanf("%s", &Agenda[cont].nome); fflush(stdin); 
    printf ("Telefone: ");
    gets(Agenda[cont].telefone); fflush(stdin); 
    printf ("Email: ");
    gets(Agenda[cont].email); fflush(stdin); 
    printf ("Aniversario [DIA]: ");
    scanf("%d", &Agenda[cont].dia); fflush(stdin);
    printf ("Aniversario [MES]: ");
    scanf("%d", &Agenda[cont].mes); fflush(stdin); 
    printf ("Aniversario [ANO]: ");
    scanf("%d", &Agenda[cont].ano); fflush(stdin); 
/*  printf ("Endereco: \n");
    printf ("Rua: ");
    gets(Agenda[cont].rua); fflush(stdin); 
    printf ("Bairro: ");
    gets(Agenda[cont].bairro); fflush(stdin); 
    printf ("Cidade: ");
    gets(Agenda[cont].cidade); fflush(stdin); 
    printf ("Estado: ");
    gets(Agenda[cont].estado); fflush(stdin); 
    printf ("Pais: ");
    gets(Agenda[cont].pais); fflush(stdin); 
    printf ("Numero: ");
    gets(Agenda[cont].numero); fflush(stdin);
    printf ("Complemento: ");
    gets(Agenda[cont].complemento); fflush(stdin);
    printf ("Cep: ");
    gets(Agenda[cont].cep); fflush(stdin); */
    printf ("Observacao: ");
    gets(Agenda[cont].observacao); fflush(stdin);
    printf ("Contato inserido na agenda!!");
    cont++;
} 

void RemoverContato () {
    printf ("Vc removeu um contato!");
} 

void AgendaCompleta () {
    int i, opcao;
    contatos:
    printf ("*******************CONTATOS*************************\n");
    printf ("*                                                  *\n");
    printf ("*  [1] Nome, Telefone e Email.                     *\n");
    printf ("*  [2] Todos os dados dos contatos.                *\n"); 
    printf ("*                                                  *\n");
    printf ("****************************************************\n");

    printf ("Escolha uma opcao: "); scanf("%d", &opcao);
    switch (opcao) {
        case 1:
            system ("cls");
            for(i=0;i<5;i++) { 
                if(!NomeNulo(Agenda[i].nome)) { // SO MOSTRA OS CONTATOS Q TIVEREM NOME
                    printf ("Contato[%d]\n", i);
                    printf("Nome: %s\n",Agenda[i].nome);
                    printf("Telefone: %s\n",Agenda[i].telefone);
                    printf("Email: %s\n",Agenda[i].email);
                    printf("\n"); 
                    }
                }
            break;

        case 2: 
            system ("cls");
            for(i=0;i<5;i++) { 
                if(!NomeNulo(Agenda[i].nome)) { // SO MOSTRA OS CONTATOS Q TIVEREM NOME
                    printf ("Contato[%d]\n", i);
                    printf("Nome: %s\n",Agenda[i].nome);
                    printf("Endereco: %s",Agenda[i].rua);
                    printf(", %s",Agenda[i].bairro);
                    printf(", %s",Agenda[i].cidade);
                    printf(", %s",Agenda[i].estado);
                    printf(", %s\n",Agenda[i].pais);
                    printf("Numero: %s\n",Agenda[i].numero);
                    printf("Complemento: %s\n",Agenda[i].complemento);
                    printf("CEP: %s\n",Agenda[i].cep);
                    printf("Telefone: %s\n",Agenda[i].telefone);
                    printf("Email: %s\n",Agenda[i].email);
                    printf("Data de aniversario: %d/%d/%d\n",Agenda[i].dia, Agenda[i].mes, Agenda[i].ano);
                    printf("Observacao: %s\n",Agenda[i].observacao);
                    printf("\n"); 
                }
            }
            break;

            default :
                system ("cls");
                printf ("\n");
                printf ("           Digite uma opcao valida\n");
                sleep (2);
                goto contatos;
                break;  
    }
}

int NomeNulo(char *s){
    return(s[0] == '\0');
}
  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site (when you have enough score).

2 answers

1

The ideal in these cases is to make a minimum, complete and verifiable example so we don’t have to read all your code, interpret it, debug it, test it, etc. But roughly the problem is that you are always entering the insertion function and starting the initial position in 1, so it will always be there that will be inserted, what is adding nothing is worth. And at the end of the function you must return the new value to the main(). You need to learn about scope of variables.

It would need to have a control that started from function main() and the position would be passed as argument in the function call which would have an appropriate parameter to receive it. In fact the function itself array agenda should be created within the main() and be passed as argument as well. All this is wrong in real codes, but for exercise can be done. You’ll still be learning the real wrong way, but at least it won’t be wrong until for an exercise.

There are several other errors in this code, including redundancy and should not use goto, prefer a while.

0


The program is inserting the contact at the cont position of the vector, which has the fixed value of 1, so it will always add the record at the same vector position. It is necessary to use a repetition loop to increment the cont variable and prevent the record from always being saved at the same position.

Browser other questions tagged

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