Куда девается элемент массива структур?

Язык С.Если пользователь вводит в массив структур два одинаковых названия для книги, куда записывается в памяти компьютера второй элемент с таким же названием? И еще один вопрос. Почему, пропускается считывание цены конфет и вес, если пользователь вводит больше символов чем 49, для название конфеты?

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

struct candy
{
    char title[50];
    float price;
    float weight;
};

void Input(candy* A)
{
    for (int i = 0; i < 4; i++)
    {
        printf_s("Enter the name of the candy: ");
        fgets(A[i].title, 49, stdin);
        printf_s("Enter the price of the candy: ");
        scanf_s("%f", &A[i].price);
        printf("Enter the weight of the candy: ");
        scanf_s("%f ", &A[i].weight);
        while (getchar() != '\n');
    }
}

void Output(candy* A)
{
    for (int i = 0; i < 4; i++)
    {
        printf("title: %s  ", A[i].title);
        printf("cost: %.2f rub  ", A[i].price);
        printf("wieght: %.2f kg\n", A[i].weight);
    }
}

int Search(candy* A)
{
    char name[100];
    printf("\nEnter the name of the candy: ");
    fgets(name, 99, stdin);
    for (int i = 0; i < 4; i++)
    {
        if (strcmp(name, A[i].title)== 0)
        {
            printf("title: %s  ", A[i].title);
            printf("price: %.2f rub  ", A[i].price);
            printf("wieght: %.2f kg", A[i].weight);
            return 0;
        }
    }

    printf("This product is not found");
}

void TOTAL_COST(candy* A)
{
    float summa = 0;
    for (int i = 0; i < 4; i++)
    {
        summa = summa + A[i].price * A[i].weight;
    }
    printf("\ntotal cost of the product in stock: %.2f rub", summa);
}

int main()
{
    struct candy A[4];
    Input(A);
    Output(A);
    TOTAL_COST(A);
    Search(A);
}

два названия

переполнение


Ответы (1 шт):

Автор решения: AlexGlebe

Второе название никуда не девается. Вы просто в Search находите первый и его выводите.

Когда заводите строку большую fgets(A[i].title, 49, stdin); в буфере stdin остаются остальные символы. А эти символы мешают при считывании чисел. Поток входа нужно заранее очистить.

fgets(A[i].title, 49, stdin);
// узнаём длину строки
size_t si = strlen ( A [ i ] . title ) ;
// если последний символ не конец строки, то читаем ещё
if ( A [ i ] . title [ si - 1 ] != '\n' ) {
  while ( fgetc ( stdin ) != '\n' ) ; }
→ Ссылка