добавление структур в массив - PullRequest
0 голосов
/ 26 марта 2020

Итак, моя проблема заключается в следующем: у меня есть продукт, похожий на продукт супермаркета, который представляет собой структуру, состоящую из идентификатора (метки), его веса и количества, и у меня есть команда, c.

То, что я хочу сделать, это добавить продукт в массив и напечатать его вес.

#include <stdio.h>

int i = 0; // counts the number of products

struct product 
{
   char ident[64]; // string that identifies the product eg. "bread"
   int weight;
   int quant;
};

struct product sistem[10]; // array of products

void add(char ident,int weight,int quant);

struct product make_product(char ident,int weight,int quant)
{
    struct product p1 = {ident,weight,quant};   // creates a product and returns the created product
    return p1;
}

int main() {
    char c; int weight; char ident; int quant;
   scanf("%c %[^:]:%d:%d",&c,ident,&weight,&quant);
   add(ident,weight,quant);

   return 0;
}

void add(char ident,int weight,int quant)
{
   printf("New product %d\n",i);                           //
   sistem[i] = make_product(ident,weight,quant);           // adds a new product into an array of products
   printf("%d\n",sistem[i].weight);                       //
   i++;
}
My input: a bread:2:2

My output: New product 0
           0

Expected output: New product 0
                 2

Так что в основном это не сохранение продукта, который я создал в массиве, и я не могу понять, почему это не так.

Так что, если кто-то может помочь, я буду очень признателен.

1 Ответ

1 голос
/ 26 марта 2020

В scanf вы используете ident как один символ, но он должен быть буфером из 64 символов. Это изменение потребует изменения других частей вашего кода, чтобы ожидать char *ident. Также вы не можете инициализировать член структуры, подобный этому, тогда строкой, которая не известна во время компиляции, поэтому вы должны использовать, например, strcpy. Это должно работать

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

int i = 0; // counts the number of products

struct product 
{
   char ident[64]; // string that identifies the product eg. "bread"
   int weight;
   int quant;
};

struct product sistem[10]; // array of products

void add(char *ident,int weight,int quant);

struct product make_product(char *ident,int weight,int quant)
{
    struct product p1 = {"",weight,quant};   // creates a product and returns the created product
    strcpy(p1.ident, ident);
    return p1;
}

int main() {
    char c; int weight; char ident[64]; int quant;
   scanf("%c %[^:]:%d:%d",&c,ident,&weight,&quant);
   add(ident,weight,quant);

   return 0;
}

void add(char *ident,int weight,int quant)
{
   printf("New product %d\n",i);                           //
   sistem[i] = make_product(ident,weight,quant);           // adds a new product into an array of products
   printf("%d\n",sistem[i].weight);                       //
   i++;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...