How to store data from a struct in a vector (c++)

Asked

Viewed 205 times

-1

I’m having trouble storing information inside a vector. I need to store information like a user’s name, password and account number, so I’m using a struct

typedef struct  {
  int conta;
  string nome;
  double saldo;
  int senha;
} Cliente ;

And a vector of the struct type

vector <Cliente> clientes_;

And the role in which saving a customer’s information is this:

char opcaoMenu(char opc){
  Cliente cliente;
  do{
    cin >> opc;
    if (opc == '1'){
       acessarConta();
    }
    else if (opc =='2'){
      clientes_.push_back(cadastrarConta());
      acessarConta();
    } 
    else{
      cout << "Opção inválida! Divite novamente!" << endl<< "Escolha uma opção >>>  ";
    }
  }while (opc > '2');
  return opc;

}

The push_back registration function is this

Cliente cadastrarConta() {
  Cliente cliente;
  cin.ignore();
  cout << "Digite seu nome: ";
  getline(cin, cliente.nome);
  cout << "Digite uma senha nuḿerica: ";
  cin >> cliente.senha;
  cliente.conta = (cliente.senha + rand() % 8000 + 1000);
  cout << "Sua conta é: " << cliente.conta;

  return cliente;
}

When I give the make, I get this output in the terminal:

g++ functions.cpp main.cpp -the test. o /tmp/ccwJox4M:(.bss+0x0): multiple definitions of "clientes_" /tmp/ccyG79Ya.o:(.bss+0x0): first defined here collect2: error: Ld returned 1 Exit status make: *** [Makefile:3: all] Error 1

I just need to know where I’m going wrong. Anything the project repository is this: https://gitlab.com/peidrao/caixa-eletronico

  • Take care with using namespace, mainly in headers.

2 answers

0

Your problem is not in how to store the struct, by your error, what is happening is a problem in the link, recommend to see that answer

What I recommend to you is to move the statement of vector <Cliente> clientes_ for funcoes.cpp where is the only place you use it

Anyway it is also highly recommended not to put using namespacein headings.

Exemplifying you are loading the same things in two different files and Linker doesn’t know where to put yourself in mainor in funcoes, even with your #define it won’t work because you explicitly imported the headers into the two source codes.

0

I didn’t try to play, but if I had to kick, I’d say you’re setting clientele-in the header. This way, every time you include.hpp functions, a new definition of clientes_ is generated and "multiple definitions" happens.

To solve this, put the keyword "extern" in front of vector customers_.

extern vector <Cliente> clientes_;

With this, you will only be declaring "clientes_" and not defining. Therefore, it needs to be defined (only once). For this, in.cpp functions, write vector clients_;

vector <Cliente> clientes_;

For more details on declaration x definition, read: https://www.geeksforgeeks.org/difference-between-definition-and-declaration/

Browser other questions tagged

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