gpt4 book ai didi

c - 根据订购数量修改库存数量

转载 作者:行者123 更新时间:2023-11-30 17:55:36 24 4
gpt4 key购买 nike

我有一个名为 AddOrder() 的方法,用户可以在其中创建订单。当系统要求用户输入产品名称时,系统从 products.dat 文件中获取特定记录。然后询问用户产品数量并确认订单。确认订单记录后,我希望系统更新 products.dat 文件 y 中的库存数量,并从中减去该特定产品的产品数量。不幸的是,库存数量保持不变。这是我的代码。

void addOrder()
{
FILE *pfp;
order o1;
product p;
char ProductName[100];
int found = 0;
int choice = 0;
int tmpStock = 0;
double pPrice = 0.0;
int choice2 = 0;

ofp=fopen("orders.dat","ab");
pfp=fopen("products.dat", "rb");



printf("\n========================================================\n\n");
printf("\t\t Adding an Order\n\n");
printf("========================================================\n\n");

do
{
printf("Enter CustomerID: \n");
scanf("%s",&o1.CustomerID);
}while(!findCustomer(o1.CustomerID));


printf("Enter Product Name: \n");
scanf("%s", ProductName);

while(1)
{
fread(&p,sizeof(p),1,pfp);

if(feof(pfp))
{
break;
}
if(strcmp(ProductName,p.ProductName)==0)
{
found = 1;
tmpStock = p.QuantityInStock;
pPrice = p.price;

}
}
if(found == 0)
{
printf("The Product was not found!\n");
OrdersSubMenu();
}

printf("Enter Product Quantities: \n");
scanf("%d", &o1.ProductQuantities);

if(o1.ProductQuantities > tmpStock)
{
printf("You have axeceeded available stock! Available Stock: %d\n", tmpStock);
printf("Do you want to enter product quantity again(press 1)\n");
printf("or order a different product(press 2)?\n");
scanf("%d", &choice);

if(choice == 1)
{
printf("Enter Product Quantities: \n");
scanf("%d", &o1.ProductQuantities);
}
else
if(choice == 2)
{
OrdersSubMenu();
}
}
else
{

printf("Product Quantity is available\n");
}

o1.TotalOrderPrice = o1.ProductQuantities * pPrice;
printf("Total Order Price: %.2f\n", o1.TotalOrderPrice);

printf("Do you want to confirm order? If yes press 1, if no press 2: \n");
scanf("%d", &choice2);

if(choice2 == 1)
{
fwrite(&o1,sizeof(o1),1,ofp);


}
else
if(choice2 == 2)
{
OrdersSubMenu();
}


printf("Order record was added to the system!\n");

tmpStock = tmpStock-o1.ProductQuantities;
p.QuantityInStock =tmpStock;


fclose(ofp);
fclose(pfp);
}

最佳答案

我希望系统更新 products.dat 文件中的库存数量

但您仅打开 products.dat 进行读取访问pfp=fopen("products.dat", "rb");

您的 fwrite 语句是 ofp,它会打开到另一个文件:ofp=fopen("orders.dat","ab");

变量ofp未声明,因此至少缺少一行代码,否则无法编译。更新:由于某种原因ofp它已经成为全局性的,但为什么呢?尽管如此,这不应该影响功能(假设是单个线程)。

编辑:要写入和写入文件,请使用“r+b”模式打开它。您需要找到您想要更新库存的产品,然后向后移动当前文件位置

fseek(pfp, -sizeof(product), SEEK_CUR);

然后fwrite新产品记录。请注意 sizeof 上的 - 符号:我们正在将当前文件位置移动到刚刚读取的记录的开头。

关于c - 根据订购数量修改库存数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14183289/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com