基本上,我想获得5种独特的草药清单(在这种情况下),包括库存号,价格等。
在获得我的数组的1个列表后,我想使用一个函数来显示库存小于5的列表以及它们的唯一代码(1,2,3 ..)如果没有打印“没有运行低任何草药“并将它们存储在文本文件中。
我的问题是如何做我在第2段中描述的内容。在案例2中调用一个函数,该函数将显示库存少于5的所有草药并将其保存在文本文件中。
非常感谢任何帮助!
#include <stdio.h>
#include <string.h>
#define user "kaiti"
#define pass "123pass!"
#define herbs 5
**void stock(int i, int code[herbs], int quantity[herbs])
{
for (i=0;i<herbs;i++){
if(quantity[i]<5)
printf("%d \t %d",code[i], quantity[i]);
}
}**
int main()
{
float price[herbs];
char username[20], password[20];
int option, i, code[herbs], quantity[herbs], consumption[herbs], choice;
//-----LOGIN PHASE-----
printf("Please Enter username:");
scanf("%s",username);
printf("\nPlease enter password:");
scanf("%s",password);
while(strcmp(username, user) != 0 || strcmp(password, pass) != 0)
{
printf("Wrong username or password try again!\n");
printf("\nPlease Enter username:");
scanf("%s",&username);
printf("\nPlease enter password:");
scanf("%s",&password);
}
printf("\nCorrect username and password.\n\nWelcome Mrs.Kaiti!\n\nWhat would you like to do?");
//-----END OF LOGIN PHASE-----
printf("\n(1)Register Herbs.\n**(2)Display herbs with stock less than 5 and store them in a text file.**\n(3)See the recomended daily dosage of a herb.\n(4)Add or deduct quantity of a herb.\n(5)Sell a herb.\nChoice: ");
scanf("%d",&option);
switch( option )
{
case 1:
for(i=0;i<herbs;i++){
printf("Enter herb code: ");
scanf("%d",&code[i]);
printf("Enter herb quantity: ");
scanf("%d",&quantity[i]);
printf("Enter recomended daily consumption: ");
scanf("%d",&consumption[i]);
printf("Enter price: ");
scanf("%f",&price[i]);
printf("Add another herb?\n(1)Yes.\n(2)Back to login screen.\n");
scanf("%d",&choice);
if (choice == 2)
return main() ;
}
**case 2:
printf("The Following herbs have a quantity less than 5: \n Code\t quantity \n");
stock(i, code, quantity);**
答案 0 :(得分:0)
您需要做的就是将printf
替换为fprintf
,如下所示:
void stock(int code[herbs], int quantity[herbs])
{
int i;
FILE *f = fopen("herbs_file_name", "w");
for (i = 0 ; i < herbs ; i++)
{
if(quantity[i] < 5)
{
fprintf(f, "%d \t %d\n", code[i], quantity[i]);
}
}
fclose(f);
}
请注意,您无需传递i
- 只需在本地声明。