Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- #pragma warning(disable: 4996)
- struct Item{ // a node to hold personal details
- char name[255];
- float price; // Price for each item.
- int quantity;
- struct Item *next;
- }*head=NULL;
- void flush(); // forward declaration of functions
- void branching(char c);
- int insert();
- void print();
- struct search();
- void delete();
- int main() { // print a menu for selection
- char ch = 'i';
- ungetc('\n', stdin); // inject input buffer with a return character
- do {
- printf("Enter your selection\n");
- printf("\ti: insert a new item\n");
- printf("\td: delete an item\n");
- printf("\tp: print all items\n");
- printf("\tq: quit \n");
- flush(); // flush input buffer
- ch = tolower(getchar());
- branching(ch);
- } while (ch != 113);
- return 0;
- }
- void flush() {
- int c;
- do {
- c = getchar();
- } while (c != '\n' && c != EOF);
- }
- void branching(char c) { // branch to different tasks
- switch (c) {
- case 'i':
- insert();
- break;
- case 'd':
- delete();
- break;
- case 'p':
- print();
- break;
- case 'q':
- break;
- default:
- printf("Invalid input\n");
- }
- }
- int insert() { // insert a new entry
- struct Item *p;
- p = malloc(sizeof(struct Item));
- if (p == 0) {
- printf("out of memory\n"); return -1;
- }
- printf("Enter name, price, quantity: \n");
- scanf("%s", p->name); // p->name is array
- scanf("%f", &p->price);
- scanf("%d", &p->quantity);
- p->next = head;
- head = p;
- return 0;
- }
- struct Item* search() { // search for position to delete
- char sname[32];
- struct Item *p = head, *b = p;
- printf("please enter the name to be searched for:\n");
- scanf("%s", sname);
- while (p != 0)
- if (stricmp(sname, p->name)== 0) {
- return p;
- }
- else {b = p; p = p->next;}
- printf("The name does not exist.\n");
- return 0;
- }
- void delete() {
- struct Item *b;
- if (head == 0) return; // nothing to delete
- b = search(); // find the position
- if (b == 0) { // free head // case 1
- free(head); // C garbage collection
- head = head->next;
- return;
- }
- if (b->next->next == 0) { // case 2
- free(b->next);
- b->next = 0;
- return;
- } else {
- free(b->next);
- b->next = b->next->next; // case 3
- return;
- }
- }
- void print(){
- float total = 0;
- // .. element to L
- // Iterate each node and print
- struct Item* n = &ShoppingList;
- do{
- printf("Item: %s\n", n->name);
- printf("Quantity: %d\n", &n->quantity);
- printf("Price: %f\n", &n->price);
- total += (&n->quantity)*(&n->price);
- n = n->next;
- }
- while(n != NULL)
- printf("Grand Total: %f\n", total);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement