Comparison in "if" does not fall where it should [duplicate]

1

What error in my code? For regardless of the answer, the result is else .

#include <stdio.h>

int
main ()
{               //variaveis
  char sigla[3];
  //programa
  printf ("Entre com a sigla do seu estado:");
  scanf ("%s", &sigla);
  if ((sigla == "RJ") || (sigla == "rj"))
    {
      printf ("\nCarioca!");
    }
  else if ((sigla == "SP") || (sigla == "sp"))
    {
      printf ("\nPaulista");
    }
  else if ((sigla == "MG") || (sigla == "mg"))
    {
      printf ("\nMineiro!");
    }
  else
    {
      printf ("\nOutros Estados!");
    }

  return 0;
}
    
asked by anonymous 24.07.2018 / 01:17

1 answer

1

You have two problems with your code. 1) is using & in something that is already a memory address. When you have an array , you already have what scanf() pends. 2) You are comparing strings as if they were characters. The current way is to buy all of the array characters. For this there is a ready function in string.h calls strcmp() .

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

int main() {
    char sigla[3];
    printf("Entre com a sigla do seu estado:");
    scanf("%s", sigla);
    if (strcmp(sigla, "RJ") == 0 || strcmp(sigla, "rj") == 0) printf ("\nCarioca!");
    else if (strcmp(sigla, "SP") == 0 || strcmp(sigla, "sp") == 0) printf ("\nPaulista");
    else if (strcmp(sigla, "MG") == 0 || strcmp(sigla, "mg") == 0) printf ("\nMineiro!");
    else printf ("\nOutros Estados!");
}

See running on ideone . And no Coding Ground . Also put it in GitHub for future reference .

    
24.07.2018 / 01:24