Comparing two strings in C

Asked

Viewed 60 times

1

I’m having a problem knowing which position the user’s CPF is registered in the user’s struct array, the problem is that when I compare lista_usuarios[i].CPF == cpf_recebido never appears.

Code I’m using to compare:

void retornar_usuario(char* cpf_recebido){
      int i;
      for(i = 0; i <= 19; i++){
        if(lista_usuarios[i].CPF == cpf_recebido){
          printf("%d", i);
        }
      }
    }

I’ve tried using the strcmp however I am not succeeding, never returns 0, always returns 1 or -1

Complete code of the program:

#include <stdio.h>
#include <string.h>

  //Informações do Usuario
  struct ficha_usuario
    {
      char Nome[50];
      char CPF[30];
    };
  struct ficha_usuario lista_usuarios[20];

  //Variavel de controle de cadastro
  int c = 0;


//Função para cadastrar o usuario
void cadastro() {

  struct ficha_usuario usuario;

  printf("\n---------- Cadastro de Usuario -----------\n\n\n");

  printf("Nome do Usuario ......: ");
  fflush(stdin);
  fgets(usuario.Nome, 50, stdin);

  printf("CPF do Usuario .......: ");
  fflush(stdin);
  fgets(usuario.CPF, 30, stdin);

  printf("\n\n --------- Dados do Usuario ---------\n\n");

  printf("Nome ............: %s", usuario.Nome);
  printf("CPF .............: %s", usuario.CPF);

  lista_usuarios[c] = usuario;
  c++;

  printf("\n\n --------- Usuario Cadastrado Com Sucesso ---------\n\n");  

}

void retornar_usuario(char* cpf_recebido){
  int i;
  for(i = 0; i <= 19; i++){
    if(lista_usuarios[i].CPF == cpf_recebido){
      printf("%d", i);
    }
  }
}

int main(void) {
  cadastro();
  cadastro();
  retornar_usuario("0123456789");

}
  • 1

    Note that when using the fgets function the character ' n' (end of line or ENTER) that you inform at the end of the input is embedded into the string. In your call you do not enter such character. Call with retornar_usuario("0123456789\n"); or, better still, handle your entries and eliminate this ' n' character from the end of each string read. Another thing: to compare strings in C use the function strcmp of <string. h>.

No answers

Browser other questions tagged

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