I can’t call a string

Asked

Viewed 86 times

1

I created an algorithm that simulates a stock of a dvd sales. It stores name, price and quantity. It has some functions and it enters them, one that informs the quantity and the price of a specific dvd and it is in her that I am having problems.

After calling the function and pulling the data from the struct, it should display the name, price and units. My problem is that I can only search and return strings with up to 3 letters.

Example: If I register and then search for "Max", it works fine, but if it is "Maax", it does not find anything.

Follow the code in case anyone can help me

void pesquisa(struct locadora v4[MAX])
{   int x;
char pesquisa[100];
printf ("\nInforme o nome de qual Dvd você quer buscar: ");
scanf("%s", &pesquisa);
for(x=0;x<MAX;x++)
    if ( strcmp ( pesquisa, v4[x].dvd)==0)
        printf ("\nO preço do dvd %s é R$ %.2f. Ele possui %d unidades em estoque!!\n", v4[x].dvd, v4[x].preco, v4[x].quant);
    else
            printf ("\nNão foi encontrado nenhum registro com esse nome");
}

1 answer

3


Your mistake is in scanf().

scanf("%s", &pesquisa);

The correct form is

scanf("%s", pesquisa);
//          ^ sem &

You can still limit the possibility of buffer overflow if you enter the maximum number of characters to read

scanf("%99s", pesquisa);

And you should always check the amount returned

if (scanf("%99s", pesquisa) != 1) /* erro */;
  • Thanks for the help, PMG, but it hasn’t worked yet. Do you have any other suggestion?

  • In the ideone works ... but you need to change the prints out of the loop, or it prints the search result for each element of the database. That is ... you can print the found as soon as you find it (and exit the function), but you have to go through the whole array until you decide it doesn’t exist, and only print negative result.

  • I looked at your code on the ideone and saw that you had set a wrong value on the struct just to make the tests easier. I was bugging because of it. Thanks

Browser other questions tagged

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