C语言自动售货机代码
![C语言自动售货机代码](https://img.360docs.net/imge1/1qcjfk20mpiacvzte96829jakds7pian-11.webp)
![C语言自动售货机代码](https://img.360docs.net/imge1/1qcjfk20mpiacvzte96829jakds7pian-92.webp)
#include
#include
#include
void GetltemName(char *item, FILE *file);
int GetltemPrice(FILE *file);
void AcceptMoney(int price);
//symbolic constant definitions
#define CAPACITY 10//max number itemavailable to vend int main(void){char name[CAPACITY][20]={0};
int price[CAPACITY]={0};
FILE *stockfile;
int i,Nitems,choice;
int listend;
stockfile=fopen("pricelist.txt","r");
if(stockfile==NULL){printf("Error initialising vend: pricelist.txt not opened");}else {//read stock from file listend=0;
Nitems=0;
do {price[Nitems]=GetltemPrice(stockfile); GetltemName(name[Nitems],stockfile);
if(price[Nitems]>0){Nitems++;}else {listend=1;}}
while(Nitems //print menu printf("***Menu***\n"); for(i=0;i %20s: %dp",i,name[i],price[i]);}//request selection printf("\n\n"); do {printf("Please make your chioce(enter CTRL-C to quit);"); scanf("%d",&choice);}while(choice<0||choice>Nitems-1); printf("%s seleted.\n",name[choice]); AcceptMoney(price[choice]); printf("\nEnjoy your %s.\n",name[choice]);}fclose(stockfile); return 0;}void GetltemName(char *item,FILE *file){int len; if(feof(file)){item[0]='\0';}else {fgets(item,20,file); len=strlen(item); if(item[len-1]=='\n'){item[len-1]='\0';}}}void AcceptMoney(int price){int money=0,coin,left; printf("Please pay %d p. 10p,5p,2p,1p accepted. No change given.\n\n",price); do {left=price; printf("Price: %d, paid: %d, to pay: %d,",price,money,left); do {printf("please enter coin: \n"); scanf("%d",&coin);}while(coin!=1&&coin!=2&&coin!=5&&coin!=10); money=money+coin; left=price-money;}while(left>0); printf("%d p paid. Thank you.",money);}int GetltemPrice(FILE *file) {int j; if(feof(file)){j='\0';}else {fscanf(file,"%d",&j);}return j;}COMMODITY FILE : pricelist.txt 40Mars Bar 40Toffee Crisp 30Kit Kat 25Toblerone 40bounty 50Topic0