我正在开发一个附加用户数据并将其添加到 csv 格式的文本文件的函数。我的问题是,当它应该提示我输入 char 变量时,它会跳过它并要求我输入产品名称。我的逻辑看起来在这里吗。感谢您提前提供任何帮助。
我的结构如下所示:
struct inventory_s
{
int productNumber;
float mfrPrice;
float retailPrice;
int numInStock;
char liveInv;
char productName[PRODUCTNAME_SZ];
};
int addProduct(void)
{
struct inventory_s newInventory;
FILE* inventoryFile = fopen("inventory.txt", "a"); //opens and writes to file
if (inventoryFile == NULL) //if file is empty
{
printf("Could not open data file\n");
return -1;
}
printf(" Please enter the new product number: ");
scanf(" %i", &newInventory.productNumber);
//input= 7000
printf("\nPlease enter the manufacturer's price: ");
scanf(" %f", &newInventory.mfrPrice);
//input= 35
printf("\nPlease enter the retail price: ");
scanf(" %f", &newInventory.retailPrice);
//input= 89.99
printf("\nPlease enter the initial number in stock: ");
scanf(" %i", &newInventory.numInStock);
//input= 2
printf("\nIs this a live animal? (1 for YES or 0 for NO): ");
scanf(" %c",&newInventory.liveInv);
//input= 1
printf("\nPlease enter the new product name (up to 20 characters): ");
scanf(" %[^\n]s", newInventory.productName);
//input= Siamese Kitten
fprintf(inventoryFile,"\n%i, %.2f,%.2f,%i,%c,%s",newInventory.productNumber, newInventory.mfrPrice, newInventory.retailPrice, newInventory.numInStock, newInventory.liveInv, newInventory.productName);
fclose(inventoryFile);
return 0;
}
输出:到inventory.txt
1000, 1.49,3.79,10,0,Fish Food
2000, 0.29,1.59,100,1,AngelFish
2001, 0.09,0.79,200,1,Guppy
5000, 2.40,5.95,10,0,Dog Collar Large
6000, 49.99,129.99,3,1,Dalmation Puppy
7000, 35.00,89.99,2,1,Siamese Kitten