How to query a struct array in C after you have already written on it?

Asked

Viewed 170 times

1

Hello, I want a help I am making a program that has a menu the registered user and then consult the registration, the problem and I am not being able to consult the "database" vector of structs.

The user registers and redirects to the menu with a complete registration message, right after he chooses to consult his registration the program asks the name of the user and uses the library string to see if the registration exists at first the idea and only printa on the screen "existing user" then increment the rest.

but when the user type the name he and automatically redirected to the function Exit() BECAUSE?

#include <stdlib.h>
#include <string.h>
#define RET 0

int qc = 1;

void menu(void);
int cadastrar(void);
void consultar(void);
void sair(void);

struct usuarios{
  char nome[30];
  int idade;
  int user;
};

int main(void)
{
  menu();
  return(RET);
}

void menu(void)
{
  int esc;
  retorno:
  printf("------------------------------------\n"
        "|  Sistema de cadastro de cliente  |\n"
        "------------------------------------\n");
  printf("====MENU=======\n"
        "1.Cadastrar   |\n"
        "2.Consultar   |\n"
        "0.Sair        |\n");
  printf("===============\n\n");
  printf("opção: ");
  scanf(" %d", &esc);
  switch(esc){
    case 1:
    cadastrar();
    case 2:
    consultar();
    case 0:
    sair();
    default:
    system("clear");
    printf("Digito invalido\n\n");
    goto retorno;
  }
}

int cadastrar()
{
  int ind;
  system("clear");
  printf("------------------------");
  printf("\n| Cadastro de usuarios |\n");
  printf("------------------------\n");
  printf("Quantos usuarios quer cadastrar? ");
  scanf("%d", &qc);
  struct usuarios info_user[qc];
  struct usuarios *ptr[qc];
  system("clear");
  for(ind=0;ind<qc;ind++){
      ptr[ind] = &info_user[ind];
      ptr[ind]->user = 1;
  }
  for(ind=0;ind<qc;ind++){
    ptr[ind] = &info_user[ind];
    printf("-------------------------\n");
    printf("|  Cadastrando usuario  |\n");
    printf("-------------------------\n");
    printf("Digite seu nome: ");
    scanf("%s", ptr[ind]->nome);
    printf("Digite sua idade: ");
    scanf("%d", &ptr[ind]->idade);
    ptr[ind] -> user++;
    system("clear");
  }
  if(qc == 1){
    printf("Usuario cadastrado com sucesso!\n\n");
  }
  else if(qc > 1){
    printf("Usuarios cadastrados com sucesso!\n\n");
  }
  menu();
  return(RET);
}

void consultar()
{
  char nomeu[30];
  int comp;
  int ind;
  struct usuarios info_user[qc];
  struct usuarios *ptr[qc];
  system("clear");
  printf("-------------------------\n"
        "|  Consultando usuario  |\n"
        "-------------------------\n");
  printf("\nDigite o nome do usuario: ");
  scanf("%s", nomeu);
  for(ind=0;ind<qc;ind++){
    ptr[ind] = &info_user[ind];
  }
  for(ind=0;ind<qc;ind++){
    comp = strcmp(nomeu, ptr[ind] -> nome);
    if(comp == 1){
      printf("User existente");
    }
  }
}

void sair()
{
  printf("Encerrando programa...");
  exit(0);
}```
  • Review the operation of the switch/case command. The way you did if you were informed 1 it will run: cadastrar(); followed by consultar(); followed by sair(); followed by system("clear"); printf("Digito invalido\n\n"); goto retorno; and, I suspect you don’t want to perform all this. Another thing to study is the scope of variables. You stated struct usuarios with global scope but declared info_user[qc] with local scope to function, that is when leaving the function cadastrar this array will cease to exist. In consultar your array has no data (it actually has memory junk).

  • Another thing: I didn’t understand the reason for using an array of pointers to struct usuarios, perhaps a confusion of concepts.

3 answers

1

The program has several structuring errors, the way you are using the operator switch that is causing this problem that you refer to in your question. that operator has the following operation:

switch(variable){
  case 1:
    Func_1() // Essa função vai ser executada se variable == 1
  case 2:
    Func() // Essa função vai ser executada se variable == 1 ou variable == 2
}

To work around this and make your program work the way you should break right after each case instruction:

switch(variable){
  case 1:
    Func_1(); // Essa função vai ser executada se variable == 1
    break;
  case 2:
    Func(); // Essa função vai ser executada se variable == 2
    break;
}

Also, you didn’t create the users globally, so as soon as you finish the registered function() that registered user is lost and in the query function() you are creating another user database only. The program calls the function Exit(0) right after the search attempt because it will never find the user and then by the operation of the switch it returns to the menu() from that point and executes the code in 'case 0'. The reason a similar error does not occur with the join() function is because you call a new menu at the end of it, so you are creating a stack of menus, which will cause performance failures as the program continues running.

0

The break problem I already solved, but how can I declare the variables with struct type vectors and a pointer with the same amount of vector, and initialize each pointer pointing to a global structure vector so that I can use other functions? If you have any way to rewrite it for me and explain, Still thanks for your help.

Note: The reason I want to use pointers, is because it’s what I’m learning at the moment, usually I create complex programs that have no need just to fix. But if there’s no way to use the pointers, no problem

The current code is like this:

#include <stdlib.h>
#include <string.h>
#define RET 0

int qc = 1;

void menu(void);
int cadastrar(void);
void consultar(void);
void sair(void);

struct usuarios{
  char nome[30];
  int idade;
  int user;
};

int main(void)
{
  menu();
  return(RET);
}

void menu(void)
{
  int esc;
  retorno:
  printf("------------------------------------\n"
        "|  Sistema de cadastro de cliente  |\n"
        "------------------------------------\n");
  printf("====MENU=======\n"
        "1.Cadastrar   |\n"
        "2.Consultar   |\n"
        "0.Sair        |\n");
  printf("===============\n\n");
  printf("opção: ");
  scanf(" %d", &esc);
  switch(esc){
    case 1:
    cadastrar();
    break;
    case 2:
    consultar();
    break;
    case 0:
    sair();
    break;
    default:
    system("clear");
    printf("Digito invalido\n\n");
    goto retorno;
  }
}

int cadastrar()
{
  int ind;
  system("clear");
  printf("------------------------");
  printf("\n| Cadastro de usuarios |\n");
  printf("------------------------\n");
  printf("Quantos usuarios quer cadastrar? ");
  scanf("%d", &qc);
  struct usuarios info_user[qc];
  struct usuarios *ptr[qc];
  system("clear");
  for(ind=0;ind<qc;ind++){
      ptr[ind] = &info_user[ind];
      ptr[ind]->user = 1;
  }
  for(ind=0;ind<qc;ind++){
    ptr[ind] = &info_user[ind];
    printf("-------------------------\n");
    printf("|  Cadastrando usuario  |\n");
    printf("-------------------------\n");
    printf("Digite seu nome: ");
    scanf("%s", ptr[ind]->nome);
    printf("Digite sua idade: ");
    scanf("%d", &ptr[ind]->idade);
    ptr[ind] -> user++;
    system("clear");
  }
  if(qc == 1){
    printf("Usuario cadastrado com sucesso!\n\n");
  }
  else if(qc > 1){
    printf("Usuarios cadastrados com sucesso!\n\n");
  }
  menu();
  return(RET);
}

void consultar()
{
  char nomeu[30];
  int comp;
  int ind;
  struct usuarios info_user[qc];
  struct usuarios *ptr[qc];
  system("clear");
  printf("-------------------------\n"
        "|  Consultando usuario  |\n"
        "-------------------------\n");
  printf("\nDigite o nome do usuario: ");
  scanf("%s", nomeu);
  for(ind=0;ind<qc;ind++){
    ptr[ind] = &info_user[ind];
  }
  for(ind=0;ind<qc;ind++){
    comp = strcmp(nomeu, ptr[ind] -> nome);
    if(comp == 1){
      printf("User existente");
    }
  }
}

void sair()
{
  printf("Encerrando programa...");
  exit(0);
}``` 

0

Just declare this snippet only once outside of any method, just like with the variable "Qc":

int qc = 1;
struct usuarios info_user[qc];
struct usuarios *ptr[qc];

The way you are using the pointers in this program has no use, but for this program you will need to use pointers (struct usuarios *ptr) and make dynamic user allocation (search functions malloc and realloc) or else make this user bank have a high ceiling value of users and you write in it (struct usuarios users[1000]). I won’t rewrite the code by fixing all these problems because you will have to review many loops that are already done but this is how you will be able to solve them.

Browser other questions tagged

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