GIDForums  

Go Back   GIDForums > Computer Programming Forums > CPP / C++ Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 07-Nov-2007, 17:59
ces123 ces123 is offline
New Member
 
Join Date: Nov 2007
Posts: 2
ces123 is on a distinguished road

Develop a UML and create a Shopping Cart class


I am new at C++ and almost finished a semester of class, however I am having problems with how to begin this program...it involves creating a vector of a certain class type, and reading the information for this vector from a file. I don't know where to start!! Any help would be appreciated (example coding would be SUPER helpful) Attached is the assignment. I have already previously made the Product class, which allows for a product with the attributes mentioned to be created with user input.

THANK YOU!!!!!!!
Attached Files
File Type: doc Assignment 8 HW.doc (30.0 KB, 10 views)
  #2  
Old 08-Nov-2007, 05:36
spxza spxza is offline
New Member
 
Join Date: Nov 2007
Posts: 1
spxza is on a distinguished road

Re: Problem for Saturday!!


Pm me and i just may help
  #3  
Old 08-Nov-2007, 06:07
davis
 
Posts: n/a

Re: Develop a UML and create a Shopping Cart class


Quantity on hand is not an attribute of Product! You need to explain this to your instructor. Inventory count is often improperly associated with the "class" of the product for convenience. However, doing so, violates good OOP practices.

Here's the STUPID thing about having "quanity on hand" contained in the Product class...

What happens when I put a Product into a shopper's shopping cart? If I'm the store, my inventory (once sold) goes down by 1 and the buyer's inventory goes up by 1. Let's say that for "Bread Mix" I have 21 units "on hand" (in inventory).

Buyer ABC purchases 1 unit. By placing the unit into his cart (a vector), I've made a copy of Product:= Bread Mix from my "catalog" of available products and placed the copy into his "shopping cart." His copy says that he has 21 on hand and so does mine. Now I must reduce my count by one and his by 20. Alternatively, I have to reassign the value of his "quantity on hand" variable to the number he intends to purchase and reassign my quantity on hand to the amount it was before he placed it into his cart less the purchased number and then reconcile the entire thing again should he later decide to remove it from his cart.

In the "real world," if we have a "real" store where there are exactly 21 bread mix items on a physical shelf, no customer or set of customers can place more than the 21 possible items into their carts. If we think about it, when does the store actually "change" their inventory status? Isn't it when the items are scanned during checkout? ...and then, once payment is made? However, in a "real store" we know that we can't have more customers placing bread mix into their carts than we have on the shelves because they are physically constrained. What constraints are we entitled to in the "virtual" world?

Let's say that I place 20 of the bread mixes into my cart, but never check out. Does that mean that there's only one item for the other patrons? (Denial of Service attack?)

Here's another thought, let's say an item is a "soft drink" and you inventory 12oz individual cans, 16oz and 24oz bottles, 2-liter bottles and "sets" of cans including 6-packs, 12-backs, 18-packs and 24-packs (cases)...each a different products such as:

"Coke (regular), 6-pack, 12oz cans"
"Coke (regular), 12-pack, 12oz cans"

...et cetera.

How do you store quantity on hand in the Product instance? What happens when someone drinks a can from their one 6-pack inventory do they then have quantity_on_hand == 5/6 ?

The notion of the product being "taxable" is foolish, too. The product should have some kind of type information that can be used in applying taxation logic. If by making a boolean we are very generally applying "type," I suppose that it is okay, but it should be noted that this is why schools do not provide education for the real world, only a set of fundamental skills, which may be all that is possible considering what they have to work with!

I think that I would need to see your implementation of the Product class in order to see if you're blindly doing whatever you can to appease the assignment, or whether or not you're trying to attack this problem from the perspective of "design matters."

I'd expect to see something along the lines of:

CPP / C++ / C Code:
#ifndef _Product_h_
#define _Product_h_

#include <iostream>
#include <string>

class Product
{
public:
    Product() :
    m_id( 0 ),
    m_price( 0.0F ),
    m_isTaxable( false ),
    m_name( "" )
    {
    }
    Product( const unsigned int id, const float price, const bool isTaxable, std::string const& name ) :
    m_id( id ),
    m_price( price ),
    m_isTaxable( isTaxable ),
    m_name( name )
    {
    }
    Product( Product const& rhs )
    {
        m_id        = rhs.m_id;
        m_price     = rhs.m_price;
        m_isTaxable = rhs.m_isTaxable;
        m_name      = rhs.m_name;
    }
    virtual ~Product()
    {
    }
    Product& operator=( Product const& rhs )
    {
        if( this != &rhs )
        {
            m_id        = rhs.m_id;
            m_price     = rhs.m_price;
            m_isTaxable = rhs.m_isTaxable;
            m_name      = rhs.m_name;
        }
        return *this;
    }
    friend std::ostream& operator<<( std::ostream& os, Product const& rhs )
    {
        os << rhs.m_id << " " << rhs.m_price << " " << rhs.m_isTaxable << " " << rhs.m_name;
        return os;
    }
    friend std::istream& operator>>( std::istream& is, Product rhs )
    {
        is >> rhs.m_id >> rhs.m_price >> rhs.m_isTaxable >> rhs.m_name;
        return is;
    }
    unsigned int getId() const
    {
        return m_id;
    }
    void setId( const unsigned int id )
    {
        // should be a unique id in the system
        m_id = id;
    }
    float getPrice() const
    {
        return m_price;
    }
    void setPrice( const float price )
    {
        // probably should have a test for price < 0
        m_price = price;
    }
    bool isTaxable() const
    {
        return m_isTaxable;
    }
    void setTaxable( const bool isTaxable )
    {
        m_isTaxable = isTaxable;
    }
    std::string getName() const
    {
        return m_name;
    }
    void setName( std::string const& name )
    {
        m_name = name;
    }
protected:
private:
    unsigned int        m_id;
    float               m_price;
    bool                m_isTaxable;
    std::string         m_name;
};

#endif // ! _Product_h_

:davis:
  #4  
Old 10-Nov-2007, 14:20
goldenice goldenice is offline
New Member
 
Join Date: Nov 2007
Posts: 3
goldenice is on a distinguished road

Re: Develop a UML and create a Shopping Cart class


So did you finish it?
  #5  
Old 10-Nov-2007, 14:52
ces123 ces123 is offline
New Member
 
Join Date: Nov 2007
Posts: 2
ces123 is on a distinguished road

Re: Develop a UML and create a Shopping Cart class


nope
not yet
its not looking good
  #6  
Old 10-Nov-2007, 18:29
davis
 
Posts: n/a

Re: Develop a UML and create a Shopping Cart class


Quote:
Originally Posted by ces123
nope
not yet
its not looking good

When is it due?

Did you read my reply? Why haven't you posted your Product class? There are a lot of things that can be done to make it easier for you.

I've written most of the Product class, a ProductFactory an InventoryManager and a ShoppingCart class...all in about 15 minutes. I started a data adapter class (I forget the name of it at the moment) but then I stopped working on it when I ran a bit longer than I wanted to on it.

Of course, you can easily write a quick hack that spews forth the "right I/O" but is "totally wrong" (in terms of "good OOP"). However if you were to turn in something akin to what I wrote, you'd probably be asked too many questions that you wouldn't know the answer to, such as why you used the Adapter, Factory Method and Singleton design patterns to help solve the problem.

Also, I didn't use a vector to store the items "purchased," I used a std::map<Product, unsigned short> instead...particularly since I moved "quantity on hand" outside of Product because it is "too stupid" to leave it in there.... Note that my implementation of operator< in Product compared the m_id members...not very helpful in some ways, but definitely easy and necessary.

I can write the "stupid" one in perhaps 10 minutes and finish the "a bit smarter" one in perhaps another 15 minutes of effort...however, I thought of implementing an "embedded FAT16 file system" inside of a binary data file in order to store transactions, inventory, cart data, etc...but that may be a bit overkill. An alternative is to use a zlib-based file that you create on the fly...but I kinda sorta didn't want to rely on any "third party" libraries, that may make compiling the code on differing platforms more "challenging." I'm fairly sure that no one is thinking of an implementation of this magnitude and scope, so you're probably better off doing the minimalist approach with a bit of input from others. Perhaps a simple ISAM?

It would certainly help to know the requirements of "moving forward" with the web server-based impl since the challenge of responding to and properly handling multiple requests adds a bit of interest to the project.


:davis:
  #7  
Old 10-Nov-2007, 21:01
goldenice goldenice is offline
New Member
 
Join Date: Nov 2007
Posts: 3
goldenice is on a distinguished road

Re: Develop a UML and create a Shopping Cart class


CPP / C++ / C Code:
#include <iostream>
#include <vector>
#include <iomanip>
#include <string>
#include <fstream>
//#include "Product.h"
using namespace std;
class Product

{  
	private:
		string name;
		long id_number;
		float price;
		int quantity;
		bool is_taxable;
		
	public:
		Product(string N, long id, float pri, int quant, bool tax);
		Product();
		void Set_name(string N);
		void Set_id(long id);
		void Set_price(float pri);
		void Set_quantity(int quant);
		void Set_taxable(bool tax);
		void Set_Product(string N, long id, float pri, int quant, bool tax);
		
		long Get_id();
		float Get_price();
		int Get_quantity();
		string Get_name();
		bool Get_taxable();
};

//  **********   Constructors   ****************
// Optional constructor
Product::Product(string N, long id, float pri, int quant, bool tax)  
{
	name = N;
	id_number = id;
	price = pri;
	quantity=quant;
	is_taxable=tax;
}

// Default Constructor 

Product::Product() {}      

//Setters

void Product::Set_name(string N)
{
	name = N;
}	
void Product::Set_id(long id)
{
	id_number = id;
}
void Product::Set_price(float pri)
{
	price = pri;
}
void Product::Set_quantity(int quant)
{
	quantity = quant;
}

void Product::Set_taxable(bool tax)
{
	is_taxable=tax;
}

void Product::Set_Product(string N, long id, float pri, int quant, bool tax)  
{
	name = N;
	id_number = id;
	price = pri;
	quantity = quant;
	is_taxable = tax;
}

//Getters

long Product::Get_id()
{
	return(id_number);
}

float Product::Get_price()
{
	return(price);
}

int Product::Get_quantity()
{
	return(quantity);
}

string Product::Get_name()
{
	return(name);
}

bool Product::Get_taxable()
{
	return(is_taxable);
}

bool Open_File(ifstream &);
int  Read_Data(vector<Product> &);
void Print_Vector( const vector<Product> & );


int main()
{
	unsigned int x=0, count;
  
	vector <Product> List(5) ;
	Product  P;
	
	count = Read_Data(List);
	cout << endl ;
	if( count > 0 )
	{
		Print_Vector(List);
		//Print_Vector_File(List);
	}
	cout <<"Press enter to continue.\n";
	cin.get();
   return 0;
}

bool Open_File(ifstream &File)
{
	string  File_name ;
	cout << "Please enter input file name: ";
	cin >> File_name ;
	File.open(File_name.c_str());
	if( File.fail() )
	{
		cout <<endl <<"Bad File Name" <<endl;
		return false ;
	}
	else
		return true ;
}

int Read_Data(vector<Product> &List)
{
	ifstream  Ins;
	Product P;
	string Name;
	long id_number;
	float price;
	int quantity;
	bool is_taxable;
	int Counter = 0;
	if (Open_File(Ins))
	{
		while(!Ins.eof() ) 
		{
			Ins >> id_number >>price>>quantity>>is_taxable>>Name; 
			//Ins.ignore(10,'\n');

			P.Set_Product(Name, id_number, price, quantity, is_taxable);
			if(List.capacity() == Counter )
			List.resize(Counter*2);			
			List[Counter] = P ;
			Counter++;
			getline(Ins , Name);		
		}
		if (Counter == 0 )
		{
			cout <<"\nEmpty data file, no data to process.  Exit the program.\n" ;
			exit(0);
		}
		List.resize(Counter);
	}
	return Counter ;
}
void Print_Vector(const vector<Product> &List)
{
	unsigned int x = 0 ;
	Product P ;
	cout <<"\n***** Capacity : "<< List.capacity() << "    Size :  "<< List.size()<<endl ;
	cout << endl <<setprecision(2)<<left<<fixed;
	cout << setfill('-')<<setw(67)<<"-"<<setfill(' ')<<endl;
	cout<<setw(25)<<"Name" << setw(15) << "ID number "<< setw(15)<<"Price" << setw(15) << "Quantity on Hand" <<endl;
	cout << setfill('-')<<setw(67)<<"-"<<setfill(' ')<<endl;
	while( x < List.size() ) 
    {
		P = List[x] ;
        cout<<setw(25)<<P.Get_name()<<""<<setw(14)<<P.Get_id()<<"" <<setw(14)<< P.Get_price() <<setw(14)<< P.Get_quantity()<<endl;
		x++;
    }
}


1231 2.23 21 0 Bread Mix
1241 1.35 200 0 Potato Chips
1251 4.50 55 0 Shreded Cheese
1235 1.99 150 0 Corn Chips
1237 3.99 100 1 Deli Meat
1237 19.99 20 1 Heat Stabilizer
2133 0.75 100 0 Lentil Soup
2135 1.70 195 0 Minestrone Soup
2137 2.55 130 1 Pine Cleaner
2199 3.99 100 1 Spot Remover
2189 3.85 50 1 Sanitizing Spray
2187 4.33 100 1 Disinfectant Cleanser
2187 6.39 100 1 Ceramic Cleanre
2186 5.66 56 0 White Mocha
2185 6.77 100 0 Hazelnut Hot Cocoa
2184 2.99 100 0 Ovaltine Classic
2183 4.88 200 0 Green Tea
2182 4.99 160 0 Iced Tea Mix
2181 3.99 150 0 Grape Juice
2179 4.99 100 0 Elmo's Punch
2177 3.50 180 0 Cranberry Juice
2177 2.99 190 0 Berry Juice
2176 3.25 200 0 Strawberry Kiwi Juice
2175 2.95 100 0 Grape Raspberry Juice
2174 3.50 170 0 Bran Cereal
2173 1.45 180 0 Cereal Puffed Corn
2172 2.99 90 0 Bagels
2171 1.45 50 0 Mini Bagels

Here is the store?

I am confuse about ordering the product, should I create another vector for that? How can add items to my cart fromt the list? These are some questions that I am stucked, thanks alot...
  #8  
Old 11-Nov-2007, 06:42
davis
 
Posts: n/a

Re: Develop a UML and create a Shopping Cart class


Quote:
Originally Posted by goldenice
CPP / C++ / C Code:
#include <iostream>
#include <vector>
#include <iomanip>
#include <string>
#include <fstream>
//#include "Product.h"
using namespace std;
class Product

{  
	private:
		string name;
		long id_number;
		float price;
		int quantity;
		bool is_taxable;
		
	public:
		Product(string N, long id, float pri, int quant, bool tax);
		Product();
		void Set_name(string N);
		void Set_id(long id);
		void Set_price(float pri);
		void Set_quantity(int quant);
		void Set_taxable(bool tax);
		void Set_Product(string N, long id, float pri, int quant, bool tax);
		
		long Get_id();
		float Get_price();
		int Get_quantity();
		string Get_name();
		bool Get_taxable();
};

//  **********   Constructors   ****************
// Optional constructor
Product::Product(string N, long id, float pri, int quant, bool tax)  
{
	name = N;
	id_number = id;
	price = pri;
	quantity=quant;
	is_taxable=tax;
}

// Default Constructor 

Product::Product() {}      

//Setters

void Product::Set_name(string N)
{
	name = N;
}	
void Product::Set_id(long id)
{
	id_number = id;
}
void Product::Set_price(float pri)
{
	price = pri;
}
void Product::Set_quantity(int quant)
{
	quantity = quant;
}

void Product::Set_taxable(bool tax)
{
	is_taxable=tax;
}

void Product::Set_Product(string N, long id, float pri, int quant, bool tax)  
{
	name = N;
	id_number = id;
	price = pri;
	quantity = quant;
	is_taxable = tax;
}

//Getters

long Product::Get_id()
{
	return(id_number);
}

float Product::Get_price()
{
	return(price);
}

int Product::Get_quantity()
{
	return(quantity);
}

string Product::Get_name()
{
	return(name);
}

bool Product::Get_taxable()
{
	return(is_taxable);
}

bool Open_File(ifstream &);
int  Read_Data(vector<Product> &);
void Print_Vector( const vector<Product> & );


int main()
{
	unsigned int x=0, count;
  
	vector <Product> List(5) ;
	Product  P;
	
	count = Read_Data(List);
	cout << endl ;
	if( count > 0 )
	{
		Print_Vector(List);
		//Print_Vector_File(List);
	}
	cout <<"Press enter to continue.\n";
	cin.get();
   return 0;
}

bool Open_File(ifstream &File)
{
	string  File_name ;
	cout << "Please enter input file name: ";
	cin >> File_name ;
	File.open(File_name.c_str());
	if( File.fail() )
	{
		cout <<endl <<"Bad File Name" <<endl;
		return false ;
	}
	else
		return true ;
}

int Read_Data(vector<Product> &List)
{
	ifstream  Ins;
	Product P;
	string Name;
	long id_number;
	float price;
	int quantity;
	bool is_taxable;
	int Counter = 0;
	if (Open_File(Ins))
	{
		while(!Ins.eof() ) 
		{
			Ins >> id_number >>price>>quantity>>is_taxable>>Name; 
			//Ins.ignore(10,'\n');

			P.Set_Product(Name, id_number, price, quantity, is_taxable);
			if(List.capacity() == Counter )
			List.resize(Counter*2);			
			List[Counter] = P ;
			Counter++;
			getline(Ins , Name);		
		}
		if (Counter == 0 )
		{
			cout <<"\nEmpty data file, no data to process.  Exit the program.\n" ;
			exit(0);
		}
		List.resize(Counter);
	}
	return Counter ;
}
void Print_Vector(const vector<Product> &List)
{
	unsigned int x = 0 ;
	Product P ;
	cout <<"\n***** Capacity : "<< List.capacity() << "    Size :  "<< List.size()<<endl ;
	cout << endl <<setprecision(2)<<left<<fixed;
	cout << setfill('-')<<setw(67)<<"-"<<setfill(' ')<<endl;
	cout<<setw(25)<<"Name" << setw(15) << "ID number "<< setw(15)<<"Price" << setw(15) << "Quantity on Hand" <<endl;
	cout << setfill('-')<<setw(67)<<"-"<<setfill(' ')<<endl;
	while( x < List.size() ) 
    {
		P = List[x] ;
        cout<<setw(25)<<P.Get_name()<<""<<setw(14)<<P.Get_id()<<"" <<setw(14)<< P.Get_price() <<setw(14)<< P.Get_quantity()<<endl;
		x++;
    }
}

Here is the store?

I am confuse about ordering the product, should I create another vector for that? How can add items to my cart fromt the list? These are some questions that I am stucked, thanks alot...


Wow, that seems like a lot of work to do when C++ will do most of it for you.

CPP / C++ / C Code:
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

class Product
{
public:
    Product() :
    m_id( 0 ),
    m_price( 0.0F ),
    m_qty_on_hand( 0 ),
    m_isTaxable( false ),
    m_name( "" )
    {
    }

    Product( const unsigned int id, const float price, const unsigned int qty_on_hand, const bool isTaxable, std::string const& name ) :
    m_id( id ),
    m_price( price ),
    m_qty_on_hand( qty_on_hand ),
    m_isTaxable( isTaxable ),
    m_name( name )
    {
    }

    Product( Product const& rhs )
    {
        m_id            = rhs.m_id;
        m_price         = rhs.m_price;
        m_qty_on_hand   = rhs.m_qty_on_hand;
        m_isTaxable     = rhs.m_isTaxable;
        m_name          = rhs.m_name;
    }

    virtual ~Product()
    {
    }

    Product& operator=( Product const& rhs )
    {
        if( this != &rhs )
        {
            m_id            = rhs.m_id;
            m_price         = rhs.m_price;
            m_qty_on_hand   = rhs.m_qty_on_hand;
            m_isTaxable     = rhs.m_isTaxable;
            m_name          = rhs.m_name;
        }
        return *this;
    }

    bool operator<( Product const& rhs ) const
    {
        return(m_id < rhs.m_id);
    };

    bool operator>( Product const& rhs ) const
    {
        return(m_id > rhs.m_id);
    }

    friend std::ostream& operator<<( std::ostream& os, Product const& rhs )
    {
    	os << setiosflags( ios::fixed | ios::showpoint ) << setprecision( 2 );
        os << rhs.m_id << " " << rhs.m_price << " " << rhs.m_qty_on_hand << " " << rhs.m_isTaxable << " " << rhs.m_name;
        return os;
    }

    friend std::istream& operator>>( std::istream& is, Product& rhs )
    {
        is >> rhs.m_id >> rhs.m_price >> rhs.m_qty_on_hand >> rhs.m_isTaxable;
        char buffer[BUFSIZ] = {0};
        is.getline( buffer, BUFSIZ );
        rhs.m_name = buffer;

        return is;
    }

    unsigned int getId() const
    {
        return m_id;
    }

    void setId( const unsigned int id )
    {
        // should be a unique id in the system
        m_id = id;
    }

    float getPrice() const
    {
        return m_price;
    }

    void setPrice( const float price )
    {
        // probably should have a test for price < 0
        m_price = price;
    }

    unsigned int getQtyOnHand()
    {
        return m_qty_on_hand;
    }

    void setQtyOnHand( const unsigned int qty_on_hand )
    {
        m_qty_on_hand = qty_on_hand;
    }

    bool isTaxable() const
    {
        return m_isTaxable;
    }

    void setTaxable( const bool isTaxable )
    {
        m_isTaxable = isTaxable;
    }

    std::string getName() const
    {
        return m_name;
    }

    void setName( std::string const& name )
    {
        m_name = name;
    }

    std::string toString()
    {
        char buffer[BUFSIZ] = {0};
        sprintf( buffer, "%d %.2f %u %d %s", m_id, m_price, m_qty_on_hand, (m_isTaxable ? 1 : 0), m_name.c_str() );
        std::string s( buffer );
        return s ;
    }

protected:
    private:
    unsigned int    m_id;
    float           m_price;
    unsigned int    m_qty_on_hand;
    bool            m_isTaxable;
    std::string     m_name;
};


typedef std::vector<Product> vProducts;

void spew_products( vProducts& v )
{
    vProducts::iterator it;
    for( it = v.begin(); it != v.end(); it++ )
    {
        cout << (*it) << endl;
    }
}

int main()
{
    vProducts v;
    cout << "Enter the filename of your products: ";
    string filename;
    cin >> filename;
    ifstream infile( filename.c_str() );
    if( infile.is_open() )
    {
        Product p;
        while( infile.good() && !infile.eof() && !infile.bad() && !infile.fail() )
        {
            infile >> p;
            if( !infile.fail() )
            {
                v.push_back( p );
            }
        }
        infile.close();
    }
    if( v.size() > 0 )
    {
        spew_products( v );
    }
    return 0;
}

Output: (note that I corrected the spelling of some of the words)

Code:
1231 2.23 21 0 Bread Mix 1241 1.35 200 0 Potato Chips 1251 4.50 55 0 Shredded Cheese 1235 1.99 150 0 Corn Chips 1237 3.99 100 1 Deli Meat 1237 19.99 20 1 Heat Stabilizer 2133 0.75 100 0 Lentil Soup 2135 1.70 195 0 Minestrone Soup 2137 2.55 130 1 Pine Cleaner 2199 3.99 100 1 Spot Remover 2189 3.85 50 1 Sanitizing Spray 2187 4.33 100 1 Disinfectant Cleanser 2187 6.39 100 1 Ceramic Cleaner 2186 5.66 56 0 White Mocha 2185 6.77 100 0 Hazelnut Hot Cocoa 2184 2.99 100 0 Ovaltine Classic 2183 4.88 200 0 Green Tea 2182 4.99 160 0 Iced Tea Mix 2181 3.99 150 0 Grape Juice 2179 4.99 100 0 Elmo's Punch 2177 3.50 180 0 Cranberry Juice 2177 2.99 190 0 Berry Juice 2176 3.25 200 0 Strawberry Kiwi Juice 2175 2.95 100 0 Grape Raspberry Juice 2174 3.50 170 0 Bran Cereal 2173 1.45 180 0 Cereal Puffed Corn 2172 2.99 90 0 Bagels 2171 1.45 50 0 Mini Bagels

If you want to do more text formatting in the streaming operator, that's fine, however, I felt that keeping the same format as the input file was probably a good choice. I included a "toString" operation that can easily be modified to beautify the output without causing the output file to be hosed.

You're going to run into some "issues" going forward by using this "wrong" method of storing quantity on hand inside of Product. However, an easy way to do it is to simply write a new file for each "customer" where the "quantity on hand" is the number of each product that they place into the cart. You can use a vector for the cart in your code, but the problem is that when you move to an HTTP-based environment where it is stateless, you'll need some way of statically opening the file, reading it into the cart adding/reducing items from the cart and other "cart management" functions. If I was going to use the "quantity on hand stored in Product" method shown here, I would probably write a class to convert the streaming output from the Cart to an HTTP cookie and back to a "Cart." For now, I'd just write the contents of the cart to a file on "checkout."

That way, for the short term, you can simply read in the customer's "cart file" and manage it. Again, I'd use a map instead of a vector where the map was:

std::map<Product, unsigned int> (where the unsigned is the quantity)

...and store quantity outside of product. But if you're going to do it with qty inside of product, a vector will work fine, but then there is nothing to say that you won't have several instances of the same product contained in the vector, each with their own "quantities" that you will somehow have to manage.


:davis:
  #9  
Old 12-Nov-2007, 14:56
goldenice goldenice is offline
New Member
 
Join Date: Nov 2007
Posts: 3
goldenice is on a distinguished road

Re: Develop a UML and create a Shopping Cart class


CPP / C++ / C Code:
#include <iostream>
#include <vector>
#include <iomanip>
#include <string>
#include <fstream>

using namespace std;
class Product

{  
	private:
		string name;
		long id_number;
		float price;
		int quantity;
		bool is_taxable;
		
	public:
		Product(string N, long id, float pri, int quant, bool tax);
		Product();
		void Set_name(string N);
		void Set_id(long id);
		void Set_price(float pri);
		void Set_quantity(int quant);
		void Set_taxable(bool tax);
		void Set_Product(string N, long id, float pri, int quant, bool tax);
		
		long Get_id();
		float Get_price();
		int Get_quantity();
		string Get_name();
		bool Get_taxable();
};

//  **********   Constructors   ****************
// Optional constructor
Product::Product(string N, long id, float pri, int quant, bool tax)  
{
	name = N;
	id_number = id;
	price = pri;
	quantity=quant;
	is_taxable=tax;
}

// Default Constructor 

Product::Product() {}      

//Setters

void Product::Set_name(string N)
{
	name = N;
}	
void Product::Set_id(long id)
{
	id_number = id;
}
void Product::Set_price(float pri)
{
	price = pri;
}
void Product::Set_quantity(int quant)
{
	quantity = quant;
}

void Product::Set_taxable(bool tax)
{
	is_taxable=tax;
}

void Product::Set_Product(string N, long id, float pri, int quant, bool tax)  
{
	name = N;
	id_number = id;
	price = pri;
	quantity = quant;
	is_taxable = tax;
}

//Getters

long Product::Get_id()
{
	return(id_number);
}

float Product::Get_price()
{
	return(price);
}

int Product::Get_quantity()
{
	return(quantity);
}

string Product::Get_name()
{
	return(name);
}

bool Product::Get_taxable()
{
	return(is_taxable);
}


bool Open_File(ifstream &);
int  Read_Data(vector<Product> &);
void Print_Vector( const vector<Product> & );
void Print_Cart( const vector<Product> & );
float Calc_Total( const vector<Product> &, bool );


int main()
{
	unsigned int x=0, y=0, z=0, count, item_quantity;
    long id; 
	bool flag=false, flag2, flag3;
	bool ca_resident;
	char answer;
	vector <Product> List(5) ;
	vector <Product> Order(1) ;
	Product  P;
	
	count = Read_Data(List);
	cout << endl ;
	if( count > 0 )
	{
		Print_Vector(List);
		//Print_Vector_File(List);
	}
	do{
	cout <<"Enter the ID of the product you want to add to cart(enter 0 to finish):";
    cin>>id;
    while(y<count)
	{
		if(List[y].Get_id()==id)
		{
			Order[z]=List[y];
			do{
			cout <<"Please enter the quantity you would like to order:";
            cin>>item_quantity;
			flag2=true;
			
			if(item_quantity>List[y].Get_quantity())
			{
				cout <<"We don't have that many in stock. We only have " <<List[y].Get_quantity()<<". Please adjust your order!\n";
			    flag2=false;
			}

			}while(!flag2);
			Order[z].Set_quantity(item_quantity);
			List[y].Set_quantity(List[y].Get_quantity()-item_quantity);
			flag=true;
			z++;
			Order.resize(z*2);
		}
		y++;
	}
	if(!flag&&id!=0)
	{
		cout <<"Item not found! Please enter a valid ID number!\n";
	}
	flag=false;
	y=0;
	item_quantity=0;
	}
	while(id!=0);
	Order.resize(z);
 
    cout <<"Are you a California resident?[y/n]";
	do{
    cin>>answer;
	if(answer=='y'||answer=='Y')
	{
		ca_resident=true;
		flag3=false;
	}
	else if (answer=='n'||answer=='N')
	{
		ca_resident=false;
		flag3=false;
	}
	else 
	{
		cout<<"You have entered an invalid answer. Enter again:[y/n]";
		flag3=true;
	}
	}while(flag3);
	cout <<"Your order:\n";
    Print_Cart(Order);
	cout <<"Total Cost: " <<Calc_Total(Order, ca_resident)<<endl;


	cout <<"Press enter to continue.\n";
	cin.get();
   return 0;
}

bool Open_File(ifstream &File)
{
	string  File_name ;
	cout << "Please enter input file name: ";
	cin >> File_name ;
	File.open(File_name.c_str());
	if( File.fail() )
	{
		cout <<endl <<"File "<<File_name<<" NOT FOUND!" <<endl;
		exit(0);
		return false ;
	}
	else
		return true ;
}

int Read_Data(vector<Product> &List)
{
	ifstream  Ins;
	Product P;
	string Name;
	long id_number;
	float price;
	int quantity;
	bool is_taxable;
	int Counter = 0;
	if (Open_File(Ins))
	{
		while(!Ins.eof() ) 
		{
			Ins >> id_number >>price>>quantity>>is_taxable>>Name;
			P.Set_Product(Name, id_number, price, quantity, is_taxable);
			if(List.capacity() == Counter )
			List.resize(Counter*2);			
			List[Counter] = P ;
			Counter++;
			getline(Ins , Name);		
		}
		if (Counter == 0 )
		{
			cout <<"\nEmpty data file, no data to process.  Exit the program.\n" ;
			exit(0);
		}
		List.resize(Counter);
	}
	return Counter ;
}
void Print_Vector(const vector<Product> &List)
{
	unsigned int x = 0 ;
	Product P ;
	cout <<"\n***** Capacity : "<< List.capacity() << "    Size :  "<< List.size()<<endl ;
	cout << endl <<setprecision(2)<<left<<fixed;
	cout << setfill('-')<<setw(67)<<"-"<<setfill(' ')<<endl;
	cout<<setw(25)<<"Name" << setw(15) << "ID number "<< setw(15)<<"Price" << setw(15) << "Quantity on Hand" <<endl;
	cout << setfill('-')<<setw(67)<<"-"<<setfill(' ')<<endl;
	while( x < List.size() ) 
    {
		P = List[x] ;
        cout<<setw(25)<<P.Get_name()<<""<<setw(14)<<P.Get_id()<<"" <<setw(14)<< P.Get_price() <<setw(14)<< P.Get_quantity()<<endl;
		x++;
    }
}

void Print_Cart(const vector<Product> &List)
{
	unsigned int x = 0 ;
	Product P ;
	cout <<"Size :  "<< List.size()<<endl ;
	cout << endl <<setprecision(2)<<left<<fixed;
	cout << setfill('-')<<setw(67)<<"-"<<setfill(' ')<<endl;
	cout<<setw(25)<<"Name" << setw(15) <<"Unit Price ($)" << setw(15) << "Quantity ordered" <<endl;
	cout << setfill('-')<<setw(67)<<"-"<<setfill(' ')<<endl;
	while( x < List.size() ) 
    {
		P = List[x] ;
        cout<<setw(25)<<P.Get_name()<<""<<setw(14)<< P.Get_price() <<setw(14)<< P.Get_quantity()<<endl;
		x++;
    }
}

float Calc_Total(const vector<Product> &Order, bool ca_resident)
{
	unsigned int x = 0 ;
	float total=0.0;
	Product P ;
	
	while( x < Order.size() ) 
    {
		P = Order[x] ;

		if(P.Get_taxable()&&ca_resident)
		{
			total=total+P.Get_price()*P.Get_quantity()*1.0775;
		}
		else total=total+P.Get_price()*P.Get_quantity();
		x++;
    }
	return total;
}


Alright here is what I got for this project. It seems ugly, but as it said in the assignment sheet it is mandatory to use vectors. Thanks a lot for help...
  #10  
Old 12-Nov-2007, 16:54
davis
 
Posts: n/a

Re: Develop a UML and create a Shopping Cart class


Quote:
Originally Posted by goldenice
CPP / C++ / C Code:
void Print_Cart(const vector<Product> &List)
{
	unsigned int x = 0 ;
	Product P ;
	cout <<"Size :  "<< List.size()<<endl ;
	cout << endl <<setprecision(2)<<left<<fixed;
	cout << setfill('-')<<setw(67)<<"-"<<setfill(' ')<<endl;
	cout<<setw(25)<<"Name" << setw(15) <<"Unit Price ($)" << setw(15) << "Quantity ordered" <<endl;
	cout << setfill('-')<<setw(67)<<"-"<<setfill(' ')<<endl;
	while( x < List.size() ) 
    {
		P = List[x] ;
        cout<<setw(25)<<P.Get_name()<<""<<setw(14)<< P.Get_price() <<setw(14)<< P.Get_quantity()<<endl;
		x++;
    }
}


...ugly and (relatively speaking) processor intensive, too.

Why do an assignment of "List[x]" to P each time? Why not use an iterator?

Here is the same implementation without all of the "extra" work being done by the "hidden" assignment operator implementation:

CPP / C++ / C Code:
void Print_Cart(const vector<Product> &List)
{
    cout <<"Size :  "<< List.size()<<endl ;
    cout << endl <<setprecision(2)<<left<<fixed;
    cout << setfill('-')<<setw(67)<<"-"<<setfill(' ')<<endl;
    cout<<setw(25)<<"Name" << setw(15) <<"Unit Price ($)" << setw(15) << "Quantity ordered" <<endl;
    cout << setfill('-')<<setw(67)<<"-"<<setfill(' ')<<endl;
    for( unsigned int ui = 0; ui < List.size(); ui++ )
    {
        cout<<setw(25)<<List[ui].Get_name()<<""<<setw(14)<< List[ui].Get_price() <<setw(14)<< List[ui].Get_quantity()<<endl;
        x++;
    }
}

Also, you've separated "x" (a bad name for what it is/does) so that it is in 3 separate places. Once in its declaration/assignment to zero, again for the comparison to List.size() and again when it is post-incremented. My modifications moved it to only where it is being used and renamed it to "ui." My name choice isn't a lot better--it follows the convention of using "i" as a looping variable but with a 'u' to show that it isn't a signed int--but at least it is restricted to a very localized block of code.

I'd recommend using spaces between your operators, but that choice is up to you. It seems rather common to not see spaces between operators in code, so I suppose that it is a matter of style. Whatever style you decide, I'd recommend applying it consistently. In just the Print_Cart function, there is a good bit of inconsistency in your application of coding style.


:davis:
 

Recent GIDBlogFirst week of IA training by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Buffer problem with CD-RWriter KieranC Computer Software Forum - Windows 2 07-Jan-2006 01:45
Graphic problem in Unreal Tournament 2004 zerox Computer Software Forum - Games 10 09-Oct-2005 12:31
Runtime Problem involving "printf" in C Program supamakia C Programming Language 2 09-Oct-2005 10:09
a significant problem after installing Xp mohammad Computer Software Forum - Windows 10 09-Aug-2005 07:03
String problem vaha C Programming Language 3 24-May-2005 18:21

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 15:08.


vBulletin, Copyright © 2000 - 2008, Jelsoft Enterprises Ltd.