所以我的问题如下,我有一个像超级市场产品这样的产品,它的结构由一个标识符(标签),其重量和数量组成,并且我的命令是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
所以基本上,这不是保存我在数组中创建的产品,我似乎无法理解为什么不是。
因此,如果有人可以帮助我,我将不胜感激。
在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++;
}