Comparison in "if" does not fall where it should

Asked

Viewed 131 times

1

What error in my code? Because regardless of the answer, the result is the 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;
}
  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

1 answer

1

There are two problems in the code. 1) is using & in something that is already a memory address. When you have a array, you already have what the scanf() wait. 2) You’re comparing strings as if they were characters. The usual way is to buy all characters from array. For this there is a function ready in the string.h flame 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!");
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

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