(Language C) I’m not really able to compare if between two chars

Asked

Viewed 39 times

-2

This is the initial menu code of the program:

    #include<stdlib.h>
    #include<stdio.h>
    #include<conio.c>
    #include<time.h>
    #include<locale.h>

    void inicio();
    void logar();
    void cadastrar();
    void sobre();
    void sair();
    void cadastroAdministrativo();
    
    int opcao;               
    char valor[];
    char token[] = "a";

    int main()  
    {
    setlocale(LC_ALL,"");      
    inicio();
    }       
       
    void inicio(){
    system("cls");
    printf("Bem vindo a central da coleta de dados da Secretaria Municipal de Gestão!\n");
    printf("1-Logar\n");
    printf("2-Cadastrar\n");
    printf("3-Sobre\n");
    printf("4-Sair\n");
    printf("Opção: ");
    scanf("%i",&opcao);
    switch (opcao){
          case 1:logar(); break;
          case 2:cadastroAdministrativo(); break;
          case 3:sobre(); break;
          case 4:sair(); break;
          }
    } 

and this is the part that this giving problem:

void cadastroAdministrativo(){
opcao = 1;     
do {
fflush(stdin);    
system("cls");        
printf("Por favor digite o token de administração:\n");
scanf("%c",&valor);

if (valor == token){
printf("Placeholder\n");
scanf("%i",&valor);               
} else {
system("cls");
printf("Você errou! deseja:\n");
printf("1-Tentar novamente\n");
printf("2-Voltar\n");
printf("Opção: ");
fflush(stdin);
scanf("%i",&opcao);
} } while(opcao == 1); 
inicio();
}

how you can see this function register Administrator(); it is called if I choose option 2 in the starting menu in the option variable, and when this function is called, I must enter the administration token (which would serve for the program to know if I am an administrator or not) and then he would authenticate and let me continue, the problem, is when I make this comparison

if (valor == token){
printf("Placeholder\n");
scanf("%i",&valor);               
}

regardless of what I type, the comparison returns a false result, as you can see the token in the variative declaration is "a" so I would have to type "a" to work, so even if I type it does not validate, regardless of what I type it always returns false so the program does not work as it should, is this.

1 answer

-1

To compare char array, use the Function strcmp, available on string.h.

You can even make a more "secure" token using a small word for example:

char token[] = "senha";
char valor[10];
....
scanf("%s",valor);

if (strcmp(token,valor == 0){
   printf("Placeholder\n");
   scanf("%i",&valor);               
} else {
  ....
}

As you can see, strcmp returns 0 (zero) when the strings are equal: https://www.cplusplus.com/reference/cstring/strcmp/

You can see it working here: insert link description here
(if you want to test, click on "Fork" and change the value to be typed in "stdin")

Browser other questions tagged

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