How do I compare two strings in c

0

Basically what I want to do. It is to receive a String on the command line. Only with the String entered, they have to be in the binary base, so I do an if to check if it is binary or not. My problem is in the if, because regardless of the value you enter. Always enters the if. - Thank you for your help!

int main(){

     char binario [50][100]={"0000","0001","0010","0011","0100","0101","0110","0111","1000","1001","1010","1011","1100","1101","1110","1111"};

     char nome [50][100];

     int contador=0;

      printf("Insira um valor");
      scanf("%s",nome[0]);

    while(nome[contador]!='
int main(){

     char binario [50][100]={"0000","0001","0010","0011","0100","0101","0110","0111","1000","1001","1010","1011","1100","1101","1110","1111"};

     char nome [50][100];

     int contador=0;

      printf("Insira um valor");
      scanf("%s",nome[0]);

    while(nome[contador]!='%pre%'){



            if (nome[0] != binario[contador])
            {
                printf("Base inicial invalida");
                break;
            }

            contador++;
     } 

     return 0;

}
'){ if (nome[0] != binario[contador]) { printf("Base inicial invalida"); break; } contador++; } return 0; }
    
asked by anonymous 23.09.2016 / 23:44

2 answers

2

Notice this expression:

if (nome[0] != binario[contador])

The result of this will be the comparison of the address of two memory pointers . These two addresses will never be equal, so it will always enter if .

What you will want is to use the strcmp function:

if (strcmp(nome[0], binario[contador]) != 0)

However, I would like to point out that your program has other problems that raise the following doubts:

  • Why declare 50 names if you only need 1?

  • Why do decimal to binary conversion using strings, table values, and trial-and-error instead of calculating successive divisions for this?

23.09.2016 / 23:50
2

You can use the strcmp function, declared in the header file (or header ) string.h . Note that the strcmp function compares the contents of strings and not its size.

Example:

strcmp(string1,string2);

The function will return you up to three values. They are:

  • = 0: The two strings are identical.
  • > 0: The first different character has a value greater than the other string .
  • < 0: The first different character has a lower value than the other string .

See example :

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

int main ()
{
  char key[] = "maçã";
  char buffer[80];
  do {
     printf ("Adivinhe minha fruta favorita? ");
     fflush (stdout);
     scanf ("%79s",buffer);
  } while (strcmp (key,buffer) != 0);
  puts ("Resposta correta!");
  return 0;
}

Output:

Adivinhe minha fruta favorita? laranja
Adivinhe minha fruta favorita? maçã
Resposta correta!

Read here and here too in English .

    
23.09.2016 / 23:59