how to do to search the right code? because when I register a code, at the time of the search I type any value and the product I registered

Asked

Viewed 20 times

1

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

int main()
{
    setlocale(LC_ALL, "Portuguese");
        
    struct cadastro
    {
        char nome[50], fornecedor[50];
        int cod_cadastro, cod_pesquisa;
    };
    struct cadastro produto;
    
    int opc;
    
    do{     
    printf("\t\t\t#######################\n");
    printf("\t\t\t#                     #\n");
    printf("\t\t\t# CADASTRO DE PRODUTO #\n");
    printf("\t\t\t#                     #\n");
    printf("\t\t\t#  1 - CADASTRAR      #\n");
    printf("\t\t\t#  2 - PESQUISAR      #\n");
    printf("\t\t\t#  3 - SAIR           #\n");
    printf("\t\t\t#                     #\n");
    printf("\t\t\t#######################\n");
    
    printf("\nSELECIONE UMA OPÇÃO: ");
    scanf("%d",&opc);
    fflush(stdin);
    system("cls");
    
    switch(opc)
    {
        
        case 1:
            printf("novo codigo: ");
            scanf("%d",&produto.cod_cadastro); printf("\n");
            fflush(stdin);
            printf("nome do produto: ");
            scanf(" %[^\n]",produto.nome);  printf("\n");
            fflush(stdin);
            printf("fornecedor: ");
            scanf(" %[^\n]",produto.fornecedor); printf("\n");
            fflush(stdin);
            printf("....gravado com sucesso!\n\n");
            
            break;
        case 2:
            printf("digite o codigo do produto: ");
            scanf("%d",&produto.cod_pesquisa);
            fflush(stdin);
            system("cls");  
                    
            printf("== PRODUTO ==\n\n");
            printf("codigo fornecido: %d",produto.cod_pesquisa); printf("\n");
            printf("Produto: %s",produto.nome); printf("\n");
            printf("Fornecedor: %s",produto.fornecedor); printf("\n\n\n");          
            break;
    }
    system("pause");
    system("cls");
}while(opc!=3);
    
    
    
    
    return 0;
}
  • Search where? You will always have only one product in your code.

  • But you don’t check anything! Whether or not it’s the only registered product.

1 answer

0


Add one more variable exclusively to pick up the typed code

int id_digitado = 0;

Then replace the variable that receives the informed code

printf("digite o codigo do produto: ");
scanf("%d",&id_digitado);

Finally, only write the product data in the console if the typed id_is equal to the product.cod_search

if(id_digitado == produto.cod_pesquisa){
   printf("== PRODUTO ==\n\n");
   printf("codigo fornecido: %d",produto.cod_pesquisa); printf("\n");
   printf("Produto: %s",produto.nome); printf("\n");
   printf("Fornecedor: %s",produto.fornecedor); printf("\n\n\n");          
 }  
 break;

Browser other questions tagged

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