虽然您的绘图和您的描述在一定程度上存在冲突,但您似乎希望能够存储多个项目或文件的数据,其中每个项目协调 grocery 值、quantity 值和 unitprice 值(类似于您将用于库存系统的基础)。
从您的绘图来看,您的 Filenr 结构成员没有多大意义。为什么?如果您的基础Item 结构坐标grocery、quantity 和unitprice,那么除非Filenr 提供了作为grocery 一部分的附加唯一 位信息, quantity, 和unitprice, 那么可以简单地省略它,你可以使用它的索引来描述grocery, quantity, 和unitprice。
此外,作为char 类型,其值将被限制为256 个值之一(-128 - 127)。如果您实际上认为这是一个可打印字符,那么您的值范围将减少到只有 96 个可打印字符。
你根据你拥有的数据定义你的结构。如果Filenr 是您输入的一部分并与grocery、quantity 和unitprice 相关联的数据,则将其作为成员添加到您的结构中。如果它只是您用来引用唯一结构的东西,那么就不需要它——除非——您可以在grocery、quantity 和unitprice 中拥有两个具有完全相同值的结构,并且您正在使用 Filenr 来消除两个相同的结构之间的歧义。否则,省略它并使用索引。
没有它,您只需创建一个结构数组。这将使您能够按任何成员值进行排序、查询和求和。打印存储(虚构)值的简单实现是:
#include <stdio.h>
typedef struct { /* your struct using a typedef for convenience */
int grocery, quantity;
double unitprice;
} item;
/* simple function to output all n struct in any array of item */
void prn_items (item *items, size_t n)
{
for (size_t i = 0; i < n; i++)
printf ("\nFilenr[%2zu]:\n grocery : %d\n quantity : %d\n unitprice : %0.4f\n",
i, items[i].grocery, items[i].quantity, items[i].unitprice);
}
int main (void) {
item files[] = {{ 31756, 22, 1.3405 }, /* made-up example data for array */
{ 7818, 83, 2.4722 },
{ 17920, 63, 1.3795 },
{ 2937, 32, 2.8648 },
{ 8423, 44, 2.6031 }};
size_t n = sizeof files / sizeof *files; /* number of elements in array */
prn_items (files, n); /* output all struct */
}
使用/输出示例
运行程序只需将所有存储的由索引协调的结构值输出为Filenr:
$ ./bin/grocerystruct
Filenr[ 0]:
grocery : 31756
quantity : 22
unitprice : 1.3405
Filenr[ 1]:
grocery : 7818
quantity : 83
unitprice : 2.4722
Filenr[ 2]:
grocery : 17920
quantity : 63
unitprice : 1.3795
Filenr[ 3]:
grocery : 2937
quantity : 32
unitprice : 2.8648
Filenr[ 4]:
grocery : 8423
quantity : 44
unitprice : 2.6031
现在,如果您的意图是将每个结构保存在单独的文件中,您可以简单地使用 sprintf() 创建一个输出文件名,其中包含基于索引的唯一后缀(或前缀)。
如果你真的想要一个 char 和 Filenr 作为你的结构的一部分,你可以简单地通过添加它作为成员来包含它,例如
typedef struct { /* your struct using a typedef for convenience */
char Filenr;
int grocery, quantity;
double unitprice;
} item;
调整代码提醒处理新增成员。
最后,您不想使用与价格相关的浮点数。 (当您由于舍入错误而亏损时,公司会生气)。最好使用相应相乘的整数值,以确保不会发生舍入错误。您可以搜索“floating point type for money”并找到有关该主题的大量附加信息。
检查一下,如果您还有其他问题,请告诉我。