How to find a name with struct

1
I'm making a code that will get the names of 5 people and the 3 gifts that she took to party, and then will be asked the name of the person and the gifts she brought to party, and show if there is or not, but when I try to compare, it never finds the name, even the name being in 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;
}
    
asked by anonymous 19.01.2018 / 23:28

1 answer

2

The search you have is correct but the way it shows the value not found, because it has a printf for each presente that it parses. Instead, what you want to do is to save 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");
}

You can also make the code more efficient by setting break to two for if the variable encontrado is already 1 , because in that case you already found it, you do not need to search any 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

    
20.01.2018 / 00:48