SlideShare a Scribd company logo
1 of 20
Download to read offline
12.9 Program: Online shopping cart (continued) (C++)
This program extends the earlier "Online shopping cart" program. (Consider first saving your
earlier program).
(1) Extend the ItemToPurchase class per the following specifications:
Parameterized constructor to assign item name, item description, item price, and item quantity
(default values of 0). (1 pt)
Public member functions
SetDescription() mutator & GetDescription() accessor (2 pts)
PrintItemCost() - Outputs the item name followed by the quantity, price, and subtotal
PrintItemDescription() - Outputs the item name and description
Private data members
string itemDescription - Initialized in default constructor to "none"
Ex. of PrintItemCost() output:
Ex. of PrintItemDescription() output:
(2) Create three new files:
ShoppingCart.h - Class declaration
ShoppingCart.cpp - Class definition
main.cpp - main() function (Note: main()'s functionality differs from the warm up)
Build the ShoppingCart class with the following specifications. Note: Some can be function
stubs (empty functions) initially, to be completed in later steps.
Default constructor
Parameterized constructor which takes the customer name and date as parameters (1 pt)
Private data members
string customerName - Initialized in default constructor to "none"
string currentDate - Initialized in default constructor to "January 1, 2016"
vector < ItemToPurchase > cartItems
Public member functions
GetCustomerName() accessor (1 pt)
GetDate() accessor (1 pt)
AddItem()
Adds an item to cartItems vector. Has parameter ItemToPurchase. Does not return anything.
RemoveItem()
Removes item from cartItems vector. Has a string (an item's name) parameter. Does not return
anything.
If item name cannot be found, output this message: Item not found in cart. Nothing removed.
ModifyItem()
Modifies an item's description, price, and/or quantity. Has parameter ItemToPurchase. Does not
return anything.
If item can be found (by name) in cart, check if parameter has default values for description,
price, and quantity. If not, modify item in cart.
If item cannot be found (by name) in cart, output this message: Item not found in cart. Nothing
modified.
GetNumItemsInCart() (2 pts)
Returns quantity of all items in cart. Has no parameters.
GetCostOfCart() (2 pts)
Determines and returns the total cost of items in cart. Has no parameters.
PrintTotal()
Outputs total of objects in cart.
If cart is empty, output this message: SHOPPING CART IS EMPTY
PrintDescriptions()
Outputs each item's description.
Ex. of PrintTotal() output:
Ex. of PrintDescriptions() output:
(3) In main(), prompt the user for a customer's name and today's date. Output the name and
date. Create an object of type ShoppingCart. (1 pt)
Ex.
(4) Implement the PrintMenu() function. PrintMenu() has a ShoppingCart parameter, and
outputs a menu of options to manipulate the shopping cart. Each option is represented by a single
character. Build and output the menu within the function.
If the an invalid character is entered, continue to prompt for a valid choice. Hint: Implement Quit
before implementing other options. Call PrintMenu() in the main() function. Continue to execute
the menu until the user enters q to Quit. (3 pts)
Ex:
(5) Implement Output shopping cart menu option. (3 pts)
Ex:
(6) Implement Output item's description menu option. (2 pts)
Ex.
(7) Implement Add item to cart menu option. (3 pts)
Ex:
(8) Implement remove item menu option. (4 pts)
Ex:
(9) Implement Change item quantity menu option. Hint: Make new ItemToPurchase object and
use ItemToPurchase modifiers before using ModifyItem() function. (5 pts)
Ex:
My Program:
#ifndef ITEMTOPURCHASE_H
#define ITEMTOPURCHASE_H
#include
#include
using namespace std;
class ItemToPurchase {
public:
ItemToPurchase();
ItemToPurchase(string itemName, double itemPrice, int itemQuantity, string
itemDescription);
void SetName(string itemName);
void SetPrice(double itemPrice);
void SetQuantity(int itemQuantity);
void SetDescription(string itemDescription);
string GetName();
double GetPrice();
int GetQuantity();
string GetDescription();
void PrintItemCost();
void PrintItemDescription();
private:
string itemName;
double itemPrice;
int itemQuantity;
string itemDescription;
};
#endif
#include
#include
#include "ItemToPurchase.h"
using namespace std;
ItemToPurchase::ItemToPurchase() {
itemName = "NoName";
itemPrice = 0.0;
itemQuantity = 0;
itemDescription = "NoDescription";
return;
}
ItemToPurchase::ItemToPurchase(string itemName, double itemPrice, int itemQuantity, string
itemDescription) {
SetName(itemName);
SetPrice(itemPrice);
SetQuantity(itemQuantity);
SetDescription(itemDescription);
return;
}
void ItemToPurchase::SetName(string item_Name) {
itemName = item_Name;
return;
}
void ItemToPurchase::SetPrice(double item_Price) {
itemPrice = item_Price;
return;
}
void ItemToPurchase::SetQuantity(int item_Quantity) {
itemQuantity = item_Quantity;
return;
}
void ItemToPurchase::SetDescription(string item_Description) {
itemDescription = item_Description;
return;
}
string ItemToPurchase::GetName() {
return itemName;
}
double ItemToPurchase::GetPrice() {
return itemPrice;
}
int ItemToPurchase::GetQuantity() {
return itemQuantity;
}
string ItemToPurchase::GetDescription() {
return itemDescription;
}
void ItemToPurchase::PrintItemCost() {
cout << itemName << " " << itemQuantity << " @ $" << itemPrice << " = $" <<
itemQuantity * itemPrice << endl;
return;
}
void ItemToPurchase::PrintItemDescription() {
cout << itemName << ": " << itemDescription << endl;
return;
}
#define SHOPPINGCART_H
#include
#include
#include
#include "ItemToPurchase.h"
using namespace std;
class ShoppingCart {
public:
ShoppingCart();
ShoppingCart(string customerName, string currentDate );
string GetCustomerName();
string GetDate();
void AddItem(ItemToPurchase);
void RemoveItem(string);
void ModifyItem(ItemToPurchase);
int GetNumItemsInCart();
int GetCostOfCart();
void PrintTotal();
void PrintDescriptions();
private:
string customerName;
string currentDate;
vector cartItems;
};
#endif
Solution
#include
using namespace std;
}
void cart :: insert()
{
product p;
int n;
cout << "ele" << elements_in_cart << " " << capacity <<" ";
if (elements_in_cart == capacity)
{
printf("cart is full ");
return;
}
p=getnode();
cout << " enter the product code ";
cin >> p->product_code;
cout << " enter the product cost ";
cin >> p->product_cost;
p->next=list;
list=p;
elements_in_cart++;
}
void cart :: remove()
{
product p;
if(list==NULL)
{
cout << "There are no products in the cart to remove ";
return;
}
p=list;
list=list->next;
cout << " removed product from the cart is:" << "product code: " << p->product_code
<<" product cost: "<< p->product_cost << " ";
}
void cart :: display()
{
product p;
p=list;
if(p==NULL)
cout << " There are no products in the cart to display ";
for (p=list;p!=NULL;p=p->next)
{
cout << "product code: " << p->product_code <<" product cost: "<< p->product_cost <<
" ";
}
}
void cart :: currentTotal()
{
product p;
int total_cost=0;
p=list;
if(p==NULL)
cout << " There are no products in the cart to display ";
for (p=list;p!=NULL;p=p->next)
{
total_cost+=p->product_cost;
cout << "product code: " << p->product_code <<" product cost: "<< p->product_cost <<
" ";
}
cout << "Current total cost :" << total_cost << " ";
}
int main()
{
cart c1;
int choice,n;
cout << " enter the cart size";
cin >> n;
c1.init(n);
do
{
cout << " t1:add an element into the cart   t2:remove an element from the cart  
t3:display elements in the car  t";
cout << "4:show last product   t5:show current total   t6:exit   ";
cout << " enter your choice:";
cin >> choice;
switch(choice)
{
case 1:
c1.insert();
break;
case 2:
c1.remove();
break;
case 3:
c1.display();
break;
case 4:
c1.showtop();
break;
case 5:
c1.currentTotal();
break;
case 6:
c1.freenode();
break;
}
}while(choice != 6);
return 0;
}
#include
#include
#include
#include
#include
#include
void cart :: insert()
{
product p;
int n, cat, pcode;
cout << "ele" << elements_in_cart << " " << capacity <<" ";
if (elements_in_cart == capacity)
{
printf("cart is full ");
return;
}
do
{
display_category();
//cout << " enter the product code ";
cin >> cat;
//cout << " enter the product cost ";
display_products_in_category(cat);
cin >> pcode;
} while(!is_product_exists(cat, pcode));
ProductDetails pdtls = get_product_details(cat, pcode);
p=getnode();
p->product_code = get_product_key(cat, pcode);
p->product_cost = pdtls.product_cost;
memset(p->product_name, '0', PRODUCT_NAME_LEN);
strcpy(p->product_name, pdtls.product_name);
p->next=list;
list=p;
elements_in_cart++;
}
void cart :: remove()
{
product p;
if(list==NULL)
{
cout << "There are no products in the cart to remove ";
return;
}
p=list;
list=list->next;
cout << " removed product from the cart is:" << "product code: " << p->product_code <<
" product name: " << p->product_name << " product cost: "<< p->product_cost << " ";
}
void cart :: display()
{
product p;
p=list;
if(p==NULL)
cout << " There are no products in the cart to display ";
for (p=list;p!=NULL;p=p->next)
{
cout << "product code: " << p->product_code << " product name: " << p->product_name
<<" product cost: "<< p->product_cost << " ";
}
}
void cart :: currentTotal()
{
product p;
int total_cost=0;
p=list;
if(p==NULL)
cout << " There are no products in the cart to display ";
for (p=list;p!=NULL;p=p->next)
{
total_cost+=p->product_cost;
cout << "product code: " << p->product_code << " product name: " <product_name <<"
product cost: "<< p->product_cost << " ";
}
cout << "Current total cost :" << total_cost << " ";
}
void print_usage(char *exe) {
printf("Usage: %s [-h] -p  ", exe);
}
int get_product_key(int category, int product_code)
{
return category * PRODUCT_KEY_MULTIPLIER + product_code;
}
std::string trim(const std::string& str,
const std::string& whitespace = " t ")
{
const std::size_t strBegin = str.find_first_not_of(whitespace);
if (strBegin == std::string::npos)
return ""; // no content
const std::size_t strEnd = str.find_last_not_of(whitespace);
const std::size_t strRange = strEnd - strBegin + 1;
return str.substr(strBegin, strRange);
}
bool insert_menu_item(const ProductDetails & pdtls)
{
std::map::iterator itr = p_category.find(pdtls.product_cat_code);
if(itr != p_category.end())
{
#ifdef DEBUG
std::cout << "product category is already added, "
<< "category code => " << pdtls.product_cat_code
<< " category name => " << pdtls.product_category
<< " proceeding to add sub items"
<< endl;
#endif
ProductMenu::iterator mitr = p_menu.find(pdtls.product_cat_code);
if(mitr == p_menu.end())
{
std::cout << " item is addd to p_category but can not find in p_menu size => " <<
p_menu.size() << endl;
return false;
}
mitr->second.insert(std::pair(pdtls.product_code, std::string(pdtls.product_name)));
#ifdef DEBUG
std::cout << "added sub menu item to the existing category, p_menu size => " <<
p_menu.size() << endl;
#endif
}
else
{
p_category.insert(std::pair (pdtls.product_cat_code, std::string(pdtls.product_category)));
std::map ps_menu;
ps_menu.clear();
ps_menu.insert(std::pair(pdtls.product_code, std::string(pdtls.product_name)));
p_menu.insert(std::pair >(pdtls.product_cat_code, ps_menu));
#ifdef DEBUG
std::cout << "item added to p_menu and now the size is => " << p_menu.size() << endl;
#endif
}
return true;
}
void display_category()
{
std::map::iterator itr = p_category.begin();
std::cout << " Choose the category from the below list " << endl;
for(; itr != p_category.end(); ++itr)
{
std::cout << itr->first << " => " << itr->second << endl;
}
std::cout << endl;
}
bool display_products_in_category(int cat)
{
ProductMenu::iterator itr = p_menu.find(cat);
if(itr == p_menu.end())
{
std::cout << "Invalid category selected. Please, select the correct category again " << endl;
return false;
}
std::cout << "Select the product from the below menu " << endl;
std::map::iterator sitr = itr->second.begin();
for(; sitr != itr->second.end(); ++sitr)
{
std::cout << sitr->first << " => " << sitr->second << endl;
}
std::cout << endl;
return true;
}
ProductDetails get_product_details(int cat, int pcode)
{
int pkey = get_product_key(cat, pcode);
std::map::iterator itr = stock_details.find(pkey);
return itr->second;
}
bool is_product_exists(int cat, int pcode)
{
int pkey = get_product_key(cat, pcode);
std::map::iterator itr = stock_details.find(pkey);
return itr != stock_details.end();
}
#endif
pdtls.product_cat_code = atoi(value.c_str());
break;
case 1:
memset(pdtls.product_category, '0', PRODUCT_NAME_LEN);
strcpy(pdtls.product_category, value.c_str());
#ifdef DEBUG
cout << "category name => " << value << endl;
#endif
break;
case 2:
pdtls.product_code = atoi(value.c_str());
#ifdef DEBUG
cout << "product code => " << value << endl;
#endif
break;
case 3:
memset(pdtls.product_name, '0', PRODUCT_NAME_LEN);
strcpy(pdtls.product_name, value.c_str());
#ifdef DEBUG
cout << "product name=> " << value << endl;
#endif
case 4:
value = trim(line.substr(sindex));
pdtls.product_cost = atoi(value.c_str());
#ifdef DEBUG
cout << "product price Rs. => " << value << endl << endl;
#endif
break;
default:
cout << "got more than expected number of delimiters. Ignoring additional values "
<< endl;
continue;
}
++n;
if(n == MAX_DELIMITER_PER_LINE)
{
std::pair::iterator, bool> ret;
int pkey = get_product_key(pdtls.product_cat_code, pdtls.product_code);
ret = stock_details.insert(std::pair(pkey, pdtls));
if(ret.second == false)
{
std::cout << "product key : " << pkey
<< " already exists. please, check the product details files with unique entries "
<< endl;
fclose(fptr);
return false;
}
insert_menu_item(pdtls);
}
found = line.find_first_of(":", sindex);
}
memset(buf, '0', MAX_CHARS_PER_LINE);
}
return true;
}
void display_product_details()
{
std::map::iterator itr = stock_details.begin();
for(; itr != stock_details.end(); ++itr)
{
std::cout << "product key => " << itr->first << endl;
std::cout << "product category code => " << itr->second.product_cat_code << endl;
std::cout << "product category name => " << itr->second.product_category << endl;
std::cout << "product code => " << itr->second.product_code << endl;
std::cout << "product name => " << itr->second.product_name << endl;
std::cout << "product cost => " << itr->second.product_cost << endl;
std::cout << endl << endl;
}
}
int main(int argc, char *argv[])
{
//extern char *optarg;
//extern int optind;
cart c1;
int choice,n,option;
string product_file;
if(argc < 2)
{
cout << "Invalid usage. Please check the usage below" << endl;
print_usage(argv[0]);
exit(EXIT_FAILURE);
}
//Specifying the expected options
//The two options l and b expect numbers as argument
while ((option = getopt(argc, argv,"hp:")) != -1) {
switch (option) {
case 'p' :
cout << "got the file " << endl;
product_file = optarg;
cout << "assigned the file " << product_file << endl;
break;
case 'h' :
print_usage(argv[0]);
exit(EXIT_SUCCESS);
break;
case '?':
cout << " ? Invalid usage. Please check the usage below" << endl;
print_usage(argv[0]);
exit(EXIT_FAILURE);
break;
default:
cout << " default : Invalid usage. Please check the usage below" << endl;
print_usage(argv[0]);
exit(EXIT_FAILURE);
}
}
cout << "getting the stock details" << endl;
bool status = get_stock_details(product_file);
if(!status)
{
cout << "Failed to load stock details from the file. Please check the file :"
<< product_file << endl;
exit(EXIT_FAILURE);
}
#ifdef DEBUG
display_product_details();
#endif
cout << " enter the cart size: ";
cin >> n;
c1.init(n);
do
{
cout << " t1:add an element into the cart   t2:remove an element from the cart  
t3:display elements in the cart  t";
cout << "4:show last product   t5:show current total   t6:exit   ";
cout << " enter your choice:";
cin >> choice;
switch(choice)
{
case 1:
c1.insert();
break;
case 2:
c1.remove();
break;
case 3:
c1.display();
break;
case 4:
c1.showtop();
break;
case 5:
c1.currentTotal();
break;
case 6:
c1.freenode();
break;
}
}while(choice != 6);
return 0;
}

More Related Content

Similar to 12.9 Program Online shopping cart (continued) (C++)This program e.pdf

Ajava oep shopping application
Ajava oep shopping applicationAjava oep shopping application
Ajava oep shopping applicationPaneliya Prince
 
You are to write a program that computes customers bill for hisher.docx
 You are to write a program that computes customers bill for hisher.docx You are to write a program that computes customers bill for hisher.docx
You are to write a program that computes customers bill for hisher.docxajoy21
 
Write a class that implements the BagInterface. BagInterface should .pdf
Write a class that implements the BagInterface.  BagInterface should .pdfWrite a class that implements the BagInterface.  BagInterface should .pdf
Write a class that implements the BagInterface. BagInterface should .pdffashiongallery1
 
Amusement Park Programming ProjectProject Outcomes1. Use the Jav.docx
Amusement Park Programming ProjectProject Outcomes1. Use the Jav.docxAmusement Park Programming ProjectProject Outcomes1. Use the Jav.docx
Amusement Park Programming ProjectProject Outcomes1. Use the Jav.docxcullenrjzsme
 
C++ help finish my code Topics class definitions, arrays of objec.pdf
C++ help finish my code Topics class definitions, arrays of objec.pdfC++ help finish my code Topics class definitions, arrays of objec.pdf
C++ help finish my code Topics class definitions, arrays of objec.pdfinfo189835
 
Program Specifications in c++ Develop an inventory management system f.docx
Program Specifications in c++ Develop an inventory management system f.docxProgram Specifications in c++ Develop an inventory management system f.docx
Program Specifications in c++ Develop an inventory management system f.docxsharold2
 
Program Specifications in c++ Develop an inventory management syste.docx
Program Specifications in c++    Develop an inventory management syste.docxProgram Specifications in c++    Develop an inventory management syste.docx
Program Specifications in c++ Develop an inventory management syste.docxsharold2
 
I keep on get a redefinition error and an undefined error.Customer.pdf
I keep on get a redefinition error and an undefined error.Customer.pdfI keep on get a redefinition error and an undefined error.Customer.pdf
I keep on get a redefinition error and an undefined error.Customer.pdfherminaherman
 
UI 모듈화로 워라밸 지키기
UI 모듈화로 워라밸 지키기UI 모듈화로 워라밸 지키기
UI 모듈화로 워라밸 지키기NAVER SHOPPING
 
Gail villanueva add muscle to your wordpress site
Gail villanueva   add muscle to your wordpress siteGail villanueva   add muscle to your wordpress site
Gail villanueva add muscle to your wordpress sitereferences
 
database propertiesjdbc.url=jdbcderbyBigJavaDB;create=true # .pdf
database propertiesjdbc.url=jdbcderbyBigJavaDB;create=true # .pdfdatabase propertiesjdbc.url=jdbcderbyBigJavaDB;create=true # .pdf
database propertiesjdbc.url=jdbcderbyBigJavaDB;create=true # .pdffashiionbeutycare
 
For the following questions, you will implement the data structure to.pdf
For the following questions, you will implement the data structure to.pdfFor the following questions, you will implement the data structure to.pdf
For the following questions, you will implement the data structure to.pdfarjunhassan8
 
1 MVC – Ajax and Modal Views AJAX stands for Asynch.docx
1  MVC – Ajax and Modal Views AJAX stands for Asynch.docx1  MVC – Ajax and Modal Views AJAX stands for Asynch.docx
1 MVC – Ajax and Modal Views AJAX stands for Asynch.docxhoney725342
 
show code and all classes with full implementation for these Program S.pdf
show code and all classes with full implementation for these Program S.pdfshow code and all classes with full implementation for these Program S.pdf
show code and all classes with full implementation for these Program S.pdfAlanSmDDyerl
 
Please the following is the currency class of perious one- class Curre.pdf
Please the following is the currency class of perious one- class Curre.pdfPlease the following is the currency class of perious one- class Curre.pdf
Please the following is the currency class of perious one- class Curre.pdfadmin463580
 
please code in c#- please note that im a complete beginner- northwind.docx
please code in c#- please note that im a complete beginner-  northwind.docxplease code in c#- please note that im a complete beginner-  northwind.docx
please code in c#- please note that im a complete beginner- northwind.docxAustinaGRPaigey
 

Similar to 12.9 Program Online shopping cart (continued) (C++)This program e.pdf (17)

Ajava oep shopping application
Ajava oep shopping applicationAjava oep shopping application
Ajava oep shopping application
 
You are to write a program that computes customers bill for hisher.docx
 You are to write a program that computes customers bill for hisher.docx You are to write a program that computes customers bill for hisher.docx
You are to write a program that computes customers bill for hisher.docx
 
Write a class that implements the BagInterface. BagInterface should .pdf
Write a class that implements the BagInterface.  BagInterface should .pdfWrite a class that implements the BagInterface.  BagInterface should .pdf
Write a class that implements the BagInterface. BagInterface should .pdf
 
Amusement Park Programming ProjectProject Outcomes1. Use the Jav.docx
Amusement Park Programming ProjectProject Outcomes1. Use the Jav.docxAmusement Park Programming ProjectProject Outcomes1. Use the Jav.docx
Amusement Park Programming ProjectProject Outcomes1. Use the Jav.docx
 
C++ help finish my code Topics class definitions, arrays of objec.pdf
C++ help finish my code Topics class definitions, arrays of objec.pdfC++ help finish my code Topics class definitions, arrays of objec.pdf
C++ help finish my code Topics class definitions, arrays of objec.pdf
 
Program Specifications in c++ Develop an inventory management system f.docx
Program Specifications in c++ Develop an inventory management system f.docxProgram Specifications in c++ Develop an inventory management system f.docx
Program Specifications in c++ Develop an inventory management system f.docx
 
Program Specifications in c++ Develop an inventory management syste.docx
Program Specifications in c++    Develop an inventory management syste.docxProgram Specifications in c++    Develop an inventory management syste.docx
Program Specifications in c++ Develop an inventory management syste.docx
 
I keep on get a redefinition error and an undefined error.Customer.pdf
I keep on get a redefinition error and an undefined error.Customer.pdfI keep on get a redefinition error and an undefined error.Customer.pdf
I keep on get a redefinition error and an undefined error.Customer.pdf
 
UI 모듈화로 워라밸 지키기
UI 모듈화로 워라밸 지키기UI 모듈화로 워라밸 지키기
UI 모듈화로 워라밸 지키기
 
Gail villanueva add muscle to your wordpress site
Gail villanueva   add muscle to your wordpress siteGail villanueva   add muscle to your wordpress site
Gail villanueva add muscle to your wordpress site
 
database propertiesjdbc.url=jdbcderbyBigJavaDB;create=true # .pdf
database propertiesjdbc.url=jdbcderbyBigJavaDB;create=true # .pdfdatabase propertiesjdbc.url=jdbcderbyBigJavaDB;create=true # .pdf
database propertiesjdbc.url=jdbcderbyBigJavaDB;create=true # .pdf
 
Zero to SOLID
Zero to SOLIDZero to SOLID
Zero to SOLID
 
For the following questions, you will implement the data structure to.pdf
For the following questions, you will implement the data structure to.pdfFor the following questions, you will implement the data structure to.pdf
For the following questions, you will implement the data structure to.pdf
 
1 MVC – Ajax and Modal Views AJAX stands for Asynch.docx
1  MVC – Ajax and Modal Views AJAX stands for Asynch.docx1  MVC – Ajax and Modal Views AJAX stands for Asynch.docx
1 MVC – Ajax and Modal Views AJAX stands for Asynch.docx
 
show code and all classes with full implementation for these Program S.pdf
show code and all classes with full implementation for these Program S.pdfshow code and all classes with full implementation for these Program S.pdf
show code and all classes with full implementation for these Program S.pdf
 
Please the following is the currency class of perious one- class Curre.pdf
Please the following is the currency class of perious one- class Curre.pdfPlease the following is the currency class of perious one- class Curre.pdf
Please the following is the currency class of perious one- class Curre.pdf
 
please code in c#- please note that im a complete beginner- northwind.docx
please code in c#- please note that im a complete beginner-  northwind.docxplease code in c#- please note that im a complete beginner-  northwind.docx
please code in c#- please note that im a complete beginner- northwind.docx
 

More from fasttracksunglass

I have been working on this ROCK, PAPER, SCISSORS project for the pa.pdf
I have been working on this ROCK, PAPER, SCISSORS project for the pa.pdfI have been working on this ROCK, PAPER, SCISSORS project for the pa.pdf
I have been working on this ROCK, PAPER, SCISSORS project for the pa.pdffasttracksunglass
 
Describe tolerance as a immunologic function. What is the consequenc.pdf
Describe tolerance as a immunologic function. What is the consequenc.pdfDescribe tolerance as a immunologic function. What is the consequenc.pdf
Describe tolerance as a immunologic function. What is the consequenc.pdffasttracksunglass
 
Answer the following question about human evolution as inferred from.pdf
Answer the following question about human evolution as inferred from.pdfAnswer the following question about human evolution as inferred from.pdf
Answer the following question about human evolution as inferred from.pdffasttracksunglass
 
40.Classification of a network as a LAN or a WAN is not relevant to .pdf
40.Classification of a network as a LAN or a WAN is not relevant to .pdf40.Classification of a network as a LAN or a WAN is not relevant to .pdf
40.Classification of a network as a LAN or a WAN is not relevant to .pdffasttracksunglass
 
A sterile item is free ofmicrobes.endospores.viruses.prions..pdf
A sterile item is free ofmicrobes.endospores.viruses.prions..pdfA sterile item is free ofmicrobes.endospores.viruses.prions..pdf
A sterile item is free ofmicrobes.endospores.viruses.prions..pdffasttracksunglass
 
Both mitochondria and chloroplasts... A. obtain electrons from water .pdf
Both mitochondria and chloroplasts... A. obtain electrons from water .pdfBoth mitochondria and chloroplasts... A. obtain electrons from water .pdf
Both mitochondria and chloroplasts... A. obtain electrons from water .pdffasttracksunglass
 
Please answer all parts thank you!Parents PrPr YY rr x   PrPr.pdf
Please answer all parts thank you!Parents PrPr YY rr x   PrPr.pdfPlease answer all parts thank you!Parents PrPr YY rr x   PrPr.pdf
Please answer all parts thank you!Parents PrPr YY rr x   PrPr.pdffasttracksunglass
 
Low platelet count it a recessively inherited trait. Reevaluation of .pdf
Low platelet count it a recessively inherited trait. Reevaluation of .pdfLow platelet count it a recessively inherited trait. Reevaluation of .pdf
Low platelet count it a recessively inherited trait. Reevaluation of .pdffasttracksunglass
 
Lists can contain other lists as elements. For example the list HAIR.pdf
Lists can contain other lists as elements. For example the list HAIR.pdfLists can contain other lists as elements. For example the list HAIR.pdf
Lists can contain other lists as elements. For example the list HAIR.pdffasttracksunglass
 
Match the modified stem to its correct definition.StolonRhizome.pdf
Match the modified stem to its correct definition.StolonRhizome.pdfMatch the modified stem to its correct definition.StolonRhizome.pdf
Match the modified stem to its correct definition.StolonRhizome.pdffasttracksunglass
 
JAVAAdd to the code at the bottom to do the following two things.pdf
JAVAAdd to the code at the bottom to do the following two things.pdfJAVAAdd to the code at the bottom to do the following two things.pdf
JAVAAdd to the code at the bottom to do the following two things.pdffasttracksunglass
 
Let (X,T) be a topological space,.A subset X. Suppose that for all x .pdf
Let (X,T) be a topological space,.A subset X. Suppose that for all x .pdfLet (X,T) be a topological space,.A subset X. Suppose that for all x .pdf
Let (X,T) be a topological space,.A subset X. Suppose that for all x .pdffasttracksunglass
 
Choose the best possible answer for each of the following multiple ch.pdf
Choose the best possible answer for each of the following multiple ch.pdfChoose the best possible answer for each of the following multiple ch.pdf
Choose the best possible answer for each of the following multiple ch.pdffasttracksunglass
 
If T is a bounded and self-adjoint operator on a Hilbert space and T_.pdf
If T is a bounded and self-adjoint operator on a Hilbert space and T_.pdfIf T is a bounded and self-adjoint operator on a Hilbert space and T_.pdf
If T is a bounded and self-adjoint operator on a Hilbert space and T_.pdffasttracksunglass
 

More from fasttracksunglass (14)

I have been working on this ROCK, PAPER, SCISSORS project for the pa.pdf
I have been working on this ROCK, PAPER, SCISSORS project for the pa.pdfI have been working on this ROCK, PAPER, SCISSORS project for the pa.pdf
I have been working on this ROCK, PAPER, SCISSORS project for the pa.pdf
 
Describe tolerance as a immunologic function. What is the consequenc.pdf
Describe tolerance as a immunologic function. What is the consequenc.pdfDescribe tolerance as a immunologic function. What is the consequenc.pdf
Describe tolerance as a immunologic function. What is the consequenc.pdf
 
Answer the following question about human evolution as inferred from.pdf
Answer the following question about human evolution as inferred from.pdfAnswer the following question about human evolution as inferred from.pdf
Answer the following question about human evolution as inferred from.pdf
 
40.Classification of a network as a LAN or a WAN is not relevant to .pdf
40.Classification of a network as a LAN or a WAN is not relevant to .pdf40.Classification of a network as a LAN or a WAN is not relevant to .pdf
40.Classification of a network as a LAN or a WAN is not relevant to .pdf
 
A sterile item is free ofmicrobes.endospores.viruses.prions..pdf
A sterile item is free ofmicrobes.endospores.viruses.prions..pdfA sterile item is free ofmicrobes.endospores.viruses.prions..pdf
A sterile item is free ofmicrobes.endospores.viruses.prions..pdf
 
Both mitochondria and chloroplasts... A. obtain electrons from water .pdf
Both mitochondria and chloroplasts... A. obtain electrons from water .pdfBoth mitochondria and chloroplasts... A. obtain electrons from water .pdf
Both mitochondria and chloroplasts... A. obtain electrons from water .pdf
 
Please answer all parts thank you!Parents PrPr YY rr x   PrPr.pdf
Please answer all parts thank you!Parents PrPr YY rr x   PrPr.pdfPlease answer all parts thank you!Parents PrPr YY rr x   PrPr.pdf
Please answer all parts thank you!Parents PrPr YY rr x   PrPr.pdf
 
Low platelet count it a recessively inherited trait. Reevaluation of .pdf
Low platelet count it a recessively inherited trait. Reevaluation of .pdfLow platelet count it a recessively inherited trait. Reevaluation of .pdf
Low platelet count it a recessively inherited trait. Reevaluation of .pdf
 
Lists can contain other lists as elements. For example the list HAIR.pdf
Lists can contain other lists as elements. For example the list HAIR.pdfLists can contain other lists as elements. For example the list HAIR.pdf
Lists can contain other lists as elements. For example the list HAIR.pdf
 
Match the modified stem to its correct definition.StolonRhizome.pdf
Match the modified stem to its correct definition.StolonRhizome.pdfMatch the modified stem to its correct definition.StolonRhizome.pdf
Match the modified stem to its correct definition.StolonRhizome.pdf
 
JAVAAdd to the code at the bottom to do the following two things.pdf
JAVAAdd to the code at the bottom to do the following two things.pdfJAVAAdd to the code at the bottom to do the following two things.pdf
JAVAAdd to the code at the bottom to do the following two things.pdf
 
Let (X,T) be a topological space,.A subset X. Suppose that for all x .pdf
Let (X,T) be a topological space,.A subset X. Suppose that for all x .pdfLet (X,T) be a topological space,.A subset X. Suppose that for all x .pdf
Let (X,T) be a topological space,.A subset X. Suppose that for all x .pdf
 
Choose the best possible answer for each of the following multiple ch.pdf
Choose the best possible answer for each of the following multiple ch.pdfChoose the best possible answer for each of the following multiple ch.pdf
Choose the best possible answer for each of the following multiple ch.pdf
 
If T is a bounded and self-adjoint operator on a Hilbert space and T_.pdf
If T is a bounded and self-adjoint operator on a Hilbert space and T_.pdfIf T is a bounded and self-adjoint operator on a Hilbert space and T_.pdf
If T is a bounded and self-adjoint operator on a Hilbert space and T_.pdf
 

Recently uploaded

Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 

Recently uploaded (20)

Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 

12.9 Program Online shopping cart (continued) (C++)This program e.pdf

  • 1. 12.9 Program: Online shopping cart (continued) (C++) This program extends the earlier "Online shopping cart" program. (Consider first saving your earlier program). (1) Extend the ItemToPurchase class per the following specifications: Parameterized constructor to assign item name, item description, item price, and item quantity (default values of 0). (1 pt) Public member functions SetDescription() mutator & GetDescription() accessor (2 pts) PrintItemCost() - Outputs the item name followed by the quantity, price, and subtotal PrintItemDescription() - Outputs the item name and description Private data members string itemDescription - Initialized in default constructor to "none" Ex. of PrintItemCost() output: Ex. of PrintItemDescription() output: (2) Create three new files: ShoppingCart.h - Class declaration ShoppingCart.cpp - Class definition main.cpp - main() function (Note: main()'s functionality differs from the warm up) Build the ShoppingCart class with the following specifications. Note: Some can be function stubs (empty functions) initially, to be completed in later steps. Default constructor Parameterized constructor which takes the customer name and date as parameters (1 pt) Private data members string customerName - Initialized in default constructor to "none" string currentDate - Initialized in default constructor to "January 1, 2016" vector < ItemToPurchase > cartItems Public member functions GetCustomerName() accessor (1 pt) GetDate() accessor (1 pt) AddItem() Adds an item to cartItems vector. Has parameter ItemToPurchase. Does not return anything. RemoveItem() Removes item from cartItems vector. Has a string (an item's name) parameter. Does not return
  • 2. anything. If item name cannot be found, output this message: Item not found in cart. Nothing removed. ModifyItem() Modifies an item's description, price, and/or quantity. Has parameter ItemToPurchase. Does not return anything. If item can be found (by name) in cart, check if parameter has default values for description, price, and quantity. If not, modify item in cart. If item cannot be found (by name) in cart, output this message: Item not found in cart. Nothing modified. GetNumItemsInCart() (2 pts) Returns quantity of all items in cart. Has no parameters. GetCostOfCart() (2 pts) Determines and returns the total cost of items in cart. Has no parameters. PrintTotal() Outputs total of objects in cart. If cart is empty, output this message: SHOPPING CART IS EMPTY PrintDescriptions() Outputs each item's description. Ex. of PrintTotal() output: Ex. of PrintDescriptions() output: (3) In main(), prompt the user for a customer's name and today's date. Output the name and date. Create an object of type ShoppingCart. (1 pt) Ex. (4) Implement the PrintMenu() function. PrintMenu() has a ShoppingCart parameter, and outputs a menu of options to manipulate the shopping cart. Each option is represented by a single character. Build and output the menu within the function. If the an invalid character is entered, continue to prompt for a valid choice. Hint: Implement Quit before implementing other options. Call PrintMenu() in the main() function. Continue to execute the menu until the user enters q to Quit. (3 pts) Ex:
  • 3. (5) Implement Output shopping cart menu option. (3 pts) Ex: (6) Implement Output item's description menu option. (2 pts) Ex. (7) Implement Add item to cart menu option. (3 pts) Ex: (8) Implement remove item menu option. (4 pts) Ex: (9) Implement Change item quantity menu option. Hint: Make new ItemToPurchase object and use ItemToPurchase modifiers before using ModifyItem() function. (5 pts) Ex: My Program: #ifndef ITEMTOPURCHASE_H #define ITEMTOPURCHASE_H #include #include using namespace std; class ItemToPurchase { public: ItemToPurchase(); ItemToPurchase(string itemName, double itemPrice, int itemQuantity, string itemDescription); void SetName(string itemName); void SetPrice(double itemPrice); void SetQuantity(int itemQuantity);
  • 4. void SetDescription(string itemDescription); string GetName(); double GetPrice(); int GetQuantity(); string GetDescription(); void PrintItemCost(); void PrintItemDescription(); private: string itemName; double itemPrice; int itemQuantity; string itemDescription; }; #endif #include #include #include "ItemToPurchase.h" using namespace std; ItemToPurchase::ItemToPurchase() { itemName = "NoName"; itemPrice = 0.0; itemQuantity = 0; itemDescription = "NoDescription"; return; } ItemToPurchase::ItemToPurchase(string itemName, double itemPrice, int itemQuantity, string itemDescription) { SetName(itemName); SetPrice(itemPrice); SetQuantity(itemQuantity); SetDescription(itemDescription); return; }
  • 5. void ItemToPurchase::SetName(string item_Name) { itemName = item_Name; return; } void ItemToPurchase::SetPrice(double item_Price) { itemPrice = item_Price; return; } void ItemToPurchase::SetQuantity(int item_Quantity) { itemQuantity = item_Quantity; return; } void ItemToPurchase::SetDescription(string item_Description) { itemDescription = item_Description; return; } string ItemToPurchase::GetName() { return itemName; } double ItemToPurchase::GetPrice() { return itemPrice; } int ItemToPurchase::GetQuantity() { return itemQuantity; } string ItemToPurchase::GetDescription() { return itemDescription; } void ItemToPurchase::PrintItemCost() { cout << itemName << " " << itemQuantity << " @ $" << itemPrice << " = $" << itemQuantity * itemPrice << endl; return; } void ItemToPurchase::PrintItemDescription() { cout << itemName << ": " << itemDescription << endl;
  • 6. return; } #define SHOPPINGCART_H #include #include #include #include "ItemToPurchase.h" using namespace std; class ShoppingCart { public: ShoppingCart(); ShoppingCart(string customerName, string currentDate ); string GetCustomerName(); string GetDate(); void AddItem(ItemToPurchase); void RemoveItem(string); void ModifyItem(ItemToPurchase); int GetNumItemsInCart(); int GetCostOfCart(); void PrintTotal(); void PrintDescriptions(); private: string customerName; string currentDate; vector cartItems; }; #endif Solution #include using namespace std;
  • 7. } void cart :: insert() { product p; int n; cout << "ele" << elements_in_cart << " " << capacity <<" "; if (elements_in_cart == capacity) { printf("cart is full "); return; } p=getnode(); cout << " enter the product code "; cin >> p->product_code; cout << " enter the product cost "; cin >> p->product_cost; p->next=list; list=p; elements_in_cart++; } void cart :: remove() { product p; if(list==NULL) { cout << "There are no products in the cart to remove "; return; } p=list; list=list->next;
  • 8. cout << " removed product from the cart is:" << "product code: " << p->product_code <<" product cost: "<< p->product_cost << " "; } void cart :: display() { product p; p=list; if(p==NULL) cout << " There are no products in the cart to display "; for (p=list;p!=NULL;p=p->next) { cout << "product code: " << p->product_code <<" product cost: "<< p->product_cost << " "; } } void cart :: currentTotal() { product p; int total_cost=0; p=list; if(p==NULL) cout << " There are no products in the cart to display "; for (p=list;p!=NULL;p=p->next) { total_cost+=p->product_cost; cout << "product code: " << p->product_code <<" product cost: "<< p->product_cost << " "; } cout << "Current total cost :" << total_cost << " "; } int main() {
  • 9. cart c1; int choice,n; cout << " enter the cart size"; cin >> n; c1.init(n); do { cout << " t1:add an element into the cart t2:remove an element from the cart t3:display elements in the car t"; cout << "4:show last product t5:show current total t6:exit "; cout << " enter your choice:"; cin >> choice; switch(choice) { case 1: c1.insert(); break; case 2: c1.remove(); break; case 3: c1.display(); break; case 4: c1.showtop(); break; case 5: c1.currentTotal(); break; case 6: c1.freenode(); break; } }while(choice != 6); return 0;
  • 10. } #include #include #include #include #include #include void cart :: insert() { product p; int n, cat, pcode; cout << "ele" << elements_in_cart << " " << capacity <<" "; if (elements_in_cart == capacity) { printf("cart is full "); return; } do { display_category(); //cout << " enter the product code "; cin >> cat; //cout << " enter the product cost "; display_products_in_category(cat); cin >> pcode; } while(!is_product_exists(cat, pcode)); ProductDetails pdtls = get_product_details(cat, pcode); p=getnode(); p->product_code = get_product_key(cat, pcode); p->product_cost = pdtls.product_cost; memset(p->product_name, '0', PRODUCT_NAME_LEN);
  • 11. strcpy(p->product_name, pdtls.product_name); p->next=list; list=p; elements_in_cart++; } void cart :: remove() { product p; if(list==NULL) { cout << "There are no products in the cart to remove "; return; } p=list; list=list->next; cout << " removed product from the cart is:" << "product code: " << p->product_code << " product name: " << p->product_name << " product cost: "<< p->product_cost << " "; } void cart :: display() { product p; p=list; if(p==NULL) cout << " There are no products in the cart to display "; for (p=list;p!=NULL;p=p->next) { cout << "product code: " << p->product_code << " product name: " << p->product_name <<" product cost: "<< p->product_cost << " "; } } void cart :: currentTotal() { product p; int total_cost=0;
  • 12. p=list; if(p==NULL) cout << " There are no products in the cart to display "; for (p=list;p!=NULL;p=p->next) { total_cost+=p->product_cost; cout << "product code: " << p->product_code << " product name: " <product_name <<" product cost: "<< p->product_cost << " "; } cout << "Current total cost :" << total_cost << " "; } void print_usage(char *exe) { printf("Usage: %s [-h] -p ", exe); } int get_product_key(int category, int product_code) { return category * PRODUCT_KEY_MULTIPLIER + product_code; } std::string trim(const std::string& str, const std::string& whitespace = " t ") { const std::size_t strBegin = str.find_first_not_of(whitespace); if (strBegin == std::string::npos) return ""; // no content const std::size_t strEnd = str.find_last_not_of(whitespace); const std::size_t strRange = strEnd - strBegin + 1; return str.substr(strBegin, strRange); } bool insert_menu_item(const ProductDetails & pdtls)
  • 13. { std::map::iterator itr = p_category.find(pdtls.product_cat_code); if(itr != p_category.end()) { #ifdef DEBUG std::cout << "product category is already added, " << "category code => " << pdtls.product_cat_code << " category name => " << pdtls.product_category << " proceeding to add sub items" << endl; #endif ProductMenu::iterator mitr = p_menu.find(pdtls.product_cat_code); if(mitr == p_menu.end()) { std::cout << " item is addd to p_category but can not find in p_menu size => " << p_menu.size() << endl; return false; } mitr->second.insert(std::pair(pdtls.product_code, std::string(pdtls.product_name))); #ifdef DEBUG std::cout << "added sub menu item to the existing category, p_menu size => " << p_menu.size() << endl; #endif } else { p_category.insert(std::pair (pdtls.product_cat_code, std::string(pdtls.product_category))); std::map ps_menu; ps_menu.clear(); ps_menu.insert(std::pair(pdtls.product_code, std::string(pdtls.product_name))); p_menu.insert(std::pair >(pdtls.product_cat_code, ps_menu));
  • 14. #ifdef DEBUG std::cout << "item added to p_menu and now the size is => " << p_menu.size() << endl; #endif } return true; } void display_category() { std::map::iterator itr = p_category.begin(); std::cout << " Choose the category from the below list " << endl; for(; itr != p_category.end(); ++itr) { std::cout << itr->first << " => " << itr->second << endl; } std::cout << endl; } bool display_products_in_category(int cat) { ProductMenu::iterator itr = p_menu.find(cat); if(itr == p_menu.end()) { std::cout << "Invalid category selected. Please, select the correct category again " << endl; return false; } std::cout << "Select the product from the below menu " << endl; std::map::iterator sitr = itr->second.begin(); for(; sitr != itr->second.end(); ++sitr) { std::cout << sitr->first << " => " << sitr->second << endl; } std::cout << endl;
  • 15. return true; } ProductDetails get_product_details(int cat, int pcode) { int pkey = get_product_key(cat, pcode); std::map::iterator itr = stock_details.find(pkey); return itr->second; } bool is_product_exists(int cat, int pcode) { int pkey = get_product_key(cat, pcode); std::map::iterator itr = stock_details.find(pkey); return itr != stock_details.end(); } #endif pdtls.product_cat_code = atoi(value.c_str()); break; case 1: memset(pdtls.product_category, '0', PRODUCT_NAME_LEN); strcpy(pdtls.product_category, value.c_str()); #ifdef DEBUG cout << "category name => " << value << endl; #endif break; case 2: pdtls.product_code = atoi(value.c_str()); #ifdef DEBUG cout << "product code => " << value << endl; #endif break;
  • 16. case 3: memset(pdtls.product_name, '0', PRODUCT_NAME_LEN); strcpy(pdtls.product_name, value.c_str()); #ifdef DEBUG cout << "product name=> " << value << endl; #endif case 4: value = trim(line.substr(sindex)); pdtls.product_cost = atoi(value.c_str()); #ifdef DEBUG cout << "product price Rs. => " << value << endl << endl; #endif break; default: cout << "got more than expected number of delimiters. Ignoring additional values " << endl; continue; } ++n; if(n == MAX_DELIMITER_PER_LINE) { std::pair::iterator, bool> ret; int pkey = get_product_key(pdtls.product_cat_code, pdtls.product_code); ret = stock_details.insert(std::pair(pkey, pdtls)); if(ret.second == false) { std::cout << "product key : " << pkey << " already exists. please, check the product details files with unique entries " << endl; fclose(fptr); return false; } insert_menu_item(pdtls);
  • 17. } found = line.find_first_of(":", sindex); } memset(buf, '0', MAX_CHARS_PER_LINE); } return true; } void display_product_details() { std::map::iterator itr = stock_details.begin(); for(; itr != stock_details.end(); ++itr) { std::cout << "product key => " << itr->first << endl; std::cout << "product category code => " << itr->second.product_cat_code << endl; std::cout << "product category name => " << itr->second.product_category << endl; std::cout << "product code => " << itr->second.product_code << endl; std::cout << "product name => " << itr->second.product_name << endl; std::cout << "product cost => " << itr->second.product_cost << endl; std::cout << endl << endl; } } int main(int argc, char *argv[]) { //extern char *optarg; //extern int optind; cart c1; int choice,n,option; string product_file; if(argc < 2) { cout << "Invalid usage. Please check the usage below" << endl; print_usage(argv[0]);
  • 18. exit(EXIT_FAILURE); } //Specifying the expected options //The two options l and b expect numbers as argument while ((option = getopt(argc, argv,"hp:")) != -1) { switch (option) { case 'p' : cout << "got the file " << endl; product_file = optarg; cout << "assigned the file " << product_file << endl; break; case 'h' : print_usage(argv[0]); exit(EXIT_SUCCESS); break; case '?': cout << " ? Invalid usage. Please check the usage below" << endl; print_usage(argv[0]); exit(EXIT_FAILURE); break; default: cout << " default : Invalid usage. Please check the usage below" << endl; print_usage(argv[0]); exit(EXIT_FAILURE); } } cout << "getting the stock details" << endl; bool status = get_stock_details(product_file); if(!status) { cout << "Failed to load stock details from the file. Please check the file :" << product_file << endl; exit(EXIT_FAILURE);
  • 19. } #ifdef DEBUG display_product_details(); #endif cout << " enter the cart size: "; cin >> n; c1.init(n); do { cout << " t1:add an element into the cart t2:remove an element from the cart t3:display elements in the cart t"; cout << "4:show last product t5:show current total t6:exit "; cout << " enter your choice:"; cin >> choice; switch(choice) { case 1: c1.insert(); break; case 2: c1.remove(); break; case 3: c1.display(); break; case 4: c1.showtop(); break; case 5: c1.currentTotal(); break; case 6: c1.freenode(); break;