How to compare a string from an array in C?

1

I have the following variables:

char nome[10][8];
int i; --> Sendo esta para o loop

I ask the user to enter 5 names and then I read the variable:

printf("Entre 5 nomes : \n");
for(i=0; i< 5 ; i++)
{
scanf("%s",nome[i]);
}

But after this, I want to compare a string from the array and see if the name is correct, and if it is, it triggers a message.

My attempt:

for (i=0; i < 1; i++) {
if (nome[i] == "Lucas de Oliveira");
printf("Idade : 18 anos, \nSexo : Masculino, \nEstado civil : Solteiro");
continue;
}

It appears the message, but it does not even finish the first for to fill in all the names, and the check is somewhat incorrect.

Screenshot:

How can I proceed to make the check correct, and if only the name that is entered that is within if , the message appears.

    
asked by anonymous 29.03.2017 / 07:55

1 answer

3

Problems:

  
  • You are using the wrong function to read the string.
  •   
  • You are not comparing the string, but the address it is in.
  •   
  • Little space in array.
  •   
  • It is not iterating as often as needed.
  •   

Start by arranging the array size:

char nome[5][20];
int i;

In an array like this, what you have are 5 lines and 20 columns , and the Marcos de Oliveira name has at least 18 characters , which should be ideal.

puts("Entre 5 nomes :");
for(i=0; i< 5 ; i++)
{
   scanf("%19[^\n]%*c",nome[i]);
}

In this part you can not use printf with \n , puts is much simpler. Of course% wont stop reading when finding empty space when used in conjunction with scanf , using this expression %s causes empty spaces to be used.

for(i=0; i < 5; i++) {
    if(!(strcmp(nome[i], "Lucas de Oliveira"))){
        printf("\nNome: %s\nIdade : 18 anos, \nSexo : Masculino, \nEstado civil : Solteiro", nome[i]);
        break;
    }
}

Here, you just need to change the expression in the %19[^\n]%*c arguments using the if function that compares two expressions, and returns strcmp if they are identical, and also 0 i < 1 that is the size of the array, otherwise it stops at the first iteration, and it does not advance to the remaining names, and of course, remove the i < 5 and put continue in place, so the iteration stops when finding the match.

Using fgets

As an alternative to expression within break , you could use scanf :

for(i=0; i< 5 ; i++)
{
    fgets(nome[i], 26, stdin);
}

As fgets keeps the fgets break, you must remove before you can compare with the desired word.

for(i=0; i < 5; i++) {
        if ((strlen(nome[i])>0) && (nome[i][strlen(nome) - 1] == '\n')){
            nome[i][strlen(nome) - 1] = '
char nome[5][20];
int i;
'; } if(!(strcmp(nome[i], "Lucas de Oliveira"))){ printf("\nNome: %s\nIdade : 18 anos, \nSexo : Masculino, \nEstado civil : Solteiro", nome[i]); break; } }
  

If none or any of the functions used here are not working, see the documentation for another alternative, or check the compiler settings in use.

    
29.03.2017 / 18:20