How to find a name with struct

Asked

Viewed 1,186 times

1

I’m making a code that will receive the names of five people and the three gifts that she took to the party, and then it will be asked the name of the person and the gifts that she brought to the party, and show whether or not there is, only that when I try to compare, never find the name, even the name being on the list.

Here is my code

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

#define pessoas 5
#define pre 3

 struct p
 {
   char nome[100];
   char presentes[3][100];
 };


  int main(int argc, char** argv)
 {
    struct p convidados[pessoas];
    char teste[100], pesquisa[100];
    int i, j;
    for(i = 0; i < pessoas; i++)
    {
      setbuf(stdin, NULL);
      scanf("%s", convidados[i].nome);
      for(j = 0; j < pre ; j++)
      {
         setbuf(stdin, NULL);
         scanf("%s", convidados[i].presentes[j]);
      }
   }
   setbuf(stdin, NULL);
   scanf("%s %s", teste, pesquisa);
   for(i = 0; i < pessoas; i++)
   {
     for(j = 0; j < pre; j++)
    {
         if(strcmp(convidados[i].nome, teste) == 0 && 
   strcmp(convidados[i].presentes[j], pesquisa) == 0)
         {
            printf("Nome encontrado:\n");
         }
         else
         {
             printf("Nao\n");
         }
     }
   }
  return 0;
}

1 answer

2


The search you have is correct but the way it shows the value found is not, because it has a printf for each presente analyzing. Instead what you want to do is to store in a variable if you found what you were looking for and only at the end of the two loops/cycles present the result to the user:

int encontrado = 0;
for(i = 0; i < pessoas; i++) {
    for(j = 0; j < pre; j++) {
        if(strcmp(convidados[i].nome, teste) == 0 &&
                strcmp(convidados[i].presentes[j], pesquisa) == 0) {
            encontrado = 1;
        }
    }
}

if (encontrado == 1){
    printf("Nome encontrado:\n");
} else {
    printf("Nao\n");
}

It can also make code more efficient by putting break both of us for case the variable encontrado be it already 1, because in this case already found soon no need to research more.

for(i = 0; i < pessoas; i++) {
    for(j = 0; j < pre; j++) {
        if(strcmp(convidados[i].nome, teste) == 0 &&
                strcmp(convidados[i].presentes[j], pesquisa) == 0) {
            encontrado = 1;
            break;
        }
    }
    if (encontrado == 1) break;
}

See how it works in Ideone

I made the array smaller to be easier to test

Browser other questions tagged

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