【问题标题】:adding structures into array将结构添加到数组中
【发布时间】:2020-03-26 16:54:57
【问题描述】:

所以我的问题如下,我有一个像超市产品这样的产品,它是一个由标识符(标签)、重量和数量组成的结构,我有一个命令是 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

所以基本上这不是保存我在数组中创建的产品,我似乎无法理解为什么不保存。

所以如果有人可以帮助我将不胜感激。

【问题讨论】:

  • 有些地方使用ident 来指代char,而在其他地方使用ident 来指代字符串,这令人困惑。

标签: c arrays structure


【解决方案1】:

在 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++;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-02
    • 2022-01-18
    • 2013-01-02
    • 1970-01-01
    相关资源
    最近更新 更多