/***
write a prog reading info and print them
-use struct : item name, quantity, price, amount(price*quantity)
-function: read item from user, use ptr as prmter
-function: print items, use ptr as prmter
-int main():
struct, ptr of struct, initialize both with NULL
handle an error where mem alloc failed->terminate
free
***/
#include <stdio.h>
#include <stdlib.h>
struct item
{
char *itemName;
int qty;
float price;
float amount;
};
void readItem(struct item *i);
void printItem(struct item *i);
int main()
{
struct item itm = { NULL, 0, 0.0, 0.0 };
struct item *pItem = NULL;
pItem = &itm;
pItem->itemName = (char *) malloc(30 * sizeof(char));
if(pItem == NULL) //an error where mem alloc failed
exit(-1); //terminate immediately
// read item
readItem(pItem);
printf("\n\n OUTPUT \n");
// print item
printItem(pItem);
free(pItem->itemName);
return 0;
}
void readItem(struct item *i)
{
printf("Enter product name: ");
scanf("%s", i->itemName);
printf("\nEnter price: ");
scanf("%f", &i->price);
printf("\nEnter quantity: ");
scanf("%d", &i->qty);
i->amount = i->qty * i->price;
}
void printItem(struct item *i)
{
printf("\nName: %s",i->itemName);
printf("\nPrice: %.2f",i->price);
printf("\nQuantity: %d",i->qty);
printf("\nTotal Amount: %.2f",i->amount);
}
To embed this project on your website, copy the following code and paste it into your website's HTML: