Hello everyone,
I have a shool project that requires me to design a cash register class that uses an inventory class and the cash register should perform the following steps:
1. ask the user for the item and quantity purchased.
2. get the item's cost
3. add 30% profit to cost to get unit item price
4. get subtotal by multipling unit price * quantity.
5. computer 6% tax rate
6. display the purchase subtotal, tax, and total on the screen
7. subtract the quantity from the onHand variable of the InventoryItem class object.


Ok so I have my program and its working like a charm, except one thing!!! I cannot get the last step to work properly. I have three classes. class for price to determine total unit price. Then I have a sale class that gets the total with tax. Here are all three classes and the cpp for the code. Please direct me on how to fix. I think I can use a counter to get the loop to work for qtySelected but not sure how. Or can I subtract the qtySelected from the inventory class itself? Any direction or ideas would be great.

EDIT: THe step 7 does work and doesnt work. For example if the first time the program runs onHand is correct (standard). Once i order 3 item 0 and I say yes to make more purchases the onHand for item 0 decreases from 12 to 9. BUT if I go in and purchase 5 more item 0s, it subtracts 5 from 12 (NOT 9!).


Content of Price Class (price.h)

//Specification file for the InventoryItem class.
#ifndef SALE2_H
#define SALE2_H
class Sale2
{
private: 
	double itemPrice;
	double profitRate;
public:
	Sale2(double price, double profit = 0.3)
	{ itemPrice = price;
	profitRate = profit; }

	double getItemPrice() const
	{ return itemPrice; }

	double getProfitRate() const
	{ return profitRate; }

	double getProfit() const
	{ return (itemPrice * profitRate); }

	double getTotalUnitPrice() const
	{ return (itemPrice + getProfit()); }
};
#endif

Contents of the sale class (sales.h)

//Specification file for the InventoryItem class.
#ifndef SALE_H
#define SALE_H

class Sale
{
private: 
	double itemCost;
	double taxRate;
	double itemPrice;
	double profitRate;
	

public:
	Sale(double cost, double rate = 0.06)
	{ itemCost = cost;
	taxRate = rate; }

	double getItemCost() const
	{ return itemCost; }

	double getTaxRate() const
	{ return taxRate; }
	
	double getTax() const
	{ return (itemCost * taxRate); }

	double getTotal() const 
	{ return (itemCost + getTax()); }
};
#endif

content of inventoryItem class (InventoryItem.h)

//Specification file for the InventoryItem class.

#ifndef INVENTORYITEM_H
#define INVENTORYITEM_H
#include <cstring>       //needed for strlen and strcpy

//constant for description's default size
const int DEFAULT_SIZE = 51;

//InventoryItem class declaration
class InventoryItem
{
private:
    char *description;      //item description
    double cost;            //item cost
    double units;              //Number of units on hand

// Private member function.
void InventoryItem::createDescription(int size, char *value)
{
    // Allocate the default amount of memory for description.
    description = new char [size+1];
        
    // Store a value in the memory.
    strcpy(description, value);
}
 
public:
	//constructor #1
	InventoryItem()
	{//store an empty string in the description attribute.
		createDescription(DEFAULT_SIZE, "");
		//initialize cost and units.
		cost = 0.0;
		units = 0; }
	
	//constrcutor #2
	InventoryItem(char *desc)
	{//allocate memory and store the description.
        createDescription(strlen(desc), desc);
        //initialize cost and units.
        cost = 0.0;
        units = 0; }

    //constructor #3
    InventoryItem(char *desc, double c, double u)
    {//allocate memory and store the description.
        createDescription(strlen(desc), desc);
        //assign values to cost and units.
        cost = c;
        units = u; }

        //Destructor
        ~InventoryItem()
        { delete [] description; }

        //Mutator functions
        void setDescription(char *d)
        { strcpy(description, d); }

        void setCost(double c)
        { cost = c; }

		void setUnits(double u)
        { units = u; }

        //Accessor functions

        const char *getDescription() const
        { return description; }

        double getCost() const
        { return cost; }

        double getUnits() const
		{ return units; }

};

#endif

Contents ofthe cpp for the progran:

//This program demonstrates a class with a destructor
#include <iostream>
#include <iomanip>
#include "price.h"
#include "Sale.h"
#include "InventoryItem.h"
using namespace std;

int main()

{
	int numSelected;
	double qtySelected;
	char again;
	double price;
	double cost;
    const int NUM_ITEMS = 5;

    InventoryItem inventory[] = {

        InventoryItem("Hammer", 6.95, 12),
        InventoryItem("Wrench", 8.75, 20),
        InventoryItem("Pliers", 3.75, 10),
        InventoryItem("Ratchet", 7.95, 14),
        InventoryItem("Screwdriver", 2.50, 22) };

do
{
	cout << "Here is a list of our current inventory" << endl;
	cout << " " << endl;
	
	cout << setw(7) << "Item Number" <<
    cout << setw(14) << "Description"
		 << setw(8) << "Cost" << setw(8)
		 <<setw(20) << "Units on Hand\n";
	cout << "------------------------------------------------------------\n";

     for (int i = 0; i < NUM_ITEMS; i++)
	 {
		 cout << setw(7) << i;
		 cout << setw(21) << inventory[i].getDescription();
		 cout << setw(14) << inventory[i].getCost();
		 if (qtySelected == 0)
		 cout << setw(7) << inventory[i].getUnits() << endl;
		 else
		 cout << setw(7) << inventory[i].getUnits() - qtySelected << endl;
	 }
	 cout << "" << endl;
	 cout << "" << endl;
	 cout << "Please enter the item number you wish to purchase: "; 
	 cin >> numSelected;

	 while((numSelected < 0) || (numSelected > 5))
	 {
		 cout << "Please enter an inventory item number 0-5: ";
		 cin >> numSelected;
	 }

	 cout << "Please enter the quantity you wish to purchase: ";
	 cin >> qtySelected;
	 while(qtySelected > inventory[numSelected].getUnits())
	 {
		 cout << "Please enter quantity less than or equal to " << inventory[numSelected].getUnits() << " units: ";
		 cin >> qtySelected;
	 }
	 
	 price = inventory[numSelected].getCost();
	
	 cout << " " << endl;
	 cout << "Here is the bill: " << endl;
	 cout << " " << endl;
	 Sale2 itemSale2(price);
	 double subTotal = itemSale2.getTotalUnitPrice() * qtySelected;
	 
	 cout << "Subtotal:\t $" << subTotal << endl;
	 cost = subTotal;
	 Sale itemSale(cost);
	 
	 cout << "Sales tax:\t $" << itemSale.getTax() << endl;
	 cout << "Total:\t\t $" << itemSale.getTotal() << endl;
	 cout << "Do you want to make another purchase? ";
	 cin >> again;
	 cout << " " << endl;
}
while (again == 'Y' || again == 'y');

return 0;

}

YOu guys have worked wonders for me in the past and I am excited to see some ideas/answers. Thank you in advance.
(I know the naming conventions are off. I use very generic names when first coding to help me find things. For some reason thats how my eyes work.)

EDIT EDIT:::
I would prefer to subtract the qtySelected from the Inventory Class, any ideas how???? I am a beginner programmer so please keep that in mind with my questions/posts.

Member Avatar for r.stiltskin

Surely, if you wrote all of this code it shouldn't be much of a challenge for you to add a method to InventoryItem subtract the items sold from the units on hand.

I did write most of the code. I did not write much of the inventory code since the text book defined this class for us to use. I guess I am not understanding how they and why they designed the class the way that they did. I am not sure where to put a method to perform units - qtySelected.

Since this is for school I am just learning about classes and not 100% sure what part of the inventory class I should touch to mess around with updating the array of units on hand.

Also, I am not sure how to modify just ONE element of the array. If I get a function to work to decrease the inventory, it decreases the entire inventory by that number. So item 0, 1, 2, 3, and 4 are all decreased by qtySelected = 4 (4 units)

EDIT:
Here is the line of code on class inventory i tried to change to get it to work.

double getUnits(double qtySelected) 
		{
		if (qtySelected == 0)
			units = units;
		else
		units -= qtySelected;
		
			 return units; }

it does error out, but again if this works it subtracts qtySelected from each element's unit on hand total.

Member Avatar for r.stiltskin

Your current code is not decreasing the entire inventory -- in fact it isn't modifying the inventory at all. All it's doing is READING the quantity of each inventory item, subtracting qtySelected, and displaying the result.

YOU have to learn how the class code works, so you should study the code that you already have, and at least ATTEMPT to add a public method (function) that will adjust the inventory after a sale has been made. You'll learn more by trying, even if it initially fails, than by having someone else write it for you.

Your current code is not decreasing the entire inventory -- in fact it isn't modifying the inventory at all. All it's doing is READING the quantity of each inventory item, subtracting qtySelected, and displaying the result.

YOU have to learn how the class code works, so you should study the code that you already have, and at least ATTEMPT to add a public method (function) that will adjust the inventory after a sale has been made. You'll learn more by trying, even if it initially fails, than by having someone else write it for you.

Well I did read the book and I did ATTEMP to add a public method. My problem is I cannot get the thing to work. I tried IF ELSE statements on a public method to state if qtySelected == 0 then units = units else units -= qtySelected. Again though the problem is even if I got that part to work it would afect all the inventory and not just the on hand that was purchased. Trust me, I have tried several different ways and probably have read the chapter 5 times. I by no means plan to ever be a programmer, the only reason I take the class is for my degree program for MIS. I only need to know the basics I do not want/need to be an expert. If you could point me to readings online that you find helpful, or give me a hint that would be great. The reason I posted here was to get help not receive code. If anyone wants to post code, that great. I did not post here to be told to research the topic more and try harder. I have starred at this problem for over a week now and have other classes I must study and focus time on as well. I am not complaining about work load, I was just looking for guidance from anyone that wanted to try and help. THat is what a forum is used for correct?

So here is my public method that I ATTEMPTED to do:

ouble getUnits(double qtySelected) 
		{
		if (qtySelected == 0)
			units = units;
		else
		units -= qtySelected;
		
			 return units; }
Member Avatar for r.stiltskin

Well, actually the bit of code that you just posted should work (assuming you had a "d" at the beginning of "ouble" on the first line). But the test for 0 is unnecessary -- if for some reason you called that function when qtySelected == 0, and still did units -= qtySelected that would be fine, since units - 0 = units anyway.

But this is a function that will adjust the inventory balance after a sale is made, so "getUnits" is not a very logical name for it. Suppose you call it recordSale(). Now, you want to give it the number of units that have been sold, so it makes sense to give it that number as a parameter. Next, think about what information you want it to return. It isn't really NECESSARY for this method to return any value (mainly, it has to do what you tell it to do -- it doesn't have to "answer" you with any information, right?) so you could make it a void function. But actually, it does make sense to have it return a value, but I would suggest that, instead of returning the new unit balance, you make it return the amount ACTUALLY SUBTRACTED.

Now, as far as what goes in the body of the function, you know it needs to do is subtract qtySold from units, right? But you also want to make sure that it doesn't try to subtract a number that's greater than the amount actually in the inventory. True, you're already verifying that in your main() function, but a well-written inventory class shouldn't allow an error like that to be made by, say, a poorly written main function, so you really ought to test that the quantity is valid in the new function BEFORE doing the subtraction. And if the quantity is NOT valid (i.e. qtySold is greater than units available) don't subtract anything. Now, if qtySold is OK, return qtySold, and otherwise, don't subtract anything and return 0. That way, the return value signals to the calling function (main) that everything is OK (or not).

As far as knowing WHICH inventoryItem will be affected -- you have an array of inventoryItems, right? So, you call this function using whichever element of the array you want to adjust, and that's the one that will be affected. The same way that you use an element of the array when you query the inventory amount on line 44 of your main function.

Member Avatar for r.stiltskin

To make a long story short, I suggest that your new function should test to see if quantity sold is <= units, and if it is, then subtract quantity sold from units and return quantity sold. If it is not, then don't subtract anything and return 0.

Well, actually the bit of code that you just posted should work (assuming you had a "d" at the beginning of "ouble" on the first line). But the test for 0 is unnecessary -- if for some reason you called that function when qtySelected == 0, and still did units -= qtySelected that would be fine, since units - 0 = units anyway.

But this is a function that will adjust the inventory balance after a sale is made, so "getUnits" is not a very logical name for it. Suppose you call it recordSale(). Now, you want to give it the number of units that have been sold, so it makes sense to give it that number as a parameter. Next, think about what information you want it to return. It isn't really NECESSARY for this method to return any value (mainly, it has to do what you tell it to do -- it doesn't have to "answer" you with any information, right?) so you could make it a void function. But actually, it does make sense to have it return a value, but I would suggest that, instead of returning the new unit balance, you make it return the amount ACTUALLY SUBTRACTED.

Now, as far as what goes in the body of the function, you know it needs to do is subtract qtySold from units, right? But you also want to make sure that it doesn't try to subtract a number that's greater than the amount actually in the inventory. True, you're already verifying that in your main() function, but a well-written inventory class shouldn't allow an error like that to be made by, say, a poorly written main function, so you really ought to test that the quantity is valid in the new function BEFORE doing the subtraction. And if the quantity is NOT valid (i.e. qtySold is greater than units available) don't subtract anything. Now, if qtySold is OK, return qtySold, and otherwise, don't subtract anything and return 0. That way, the return value signals to the calling function (main) that everything is OK (or not).

As far as knowing WHICH inventoryItem will be affected -- you have an array of inventoryItems, right? So, you call this function using whichever element of the array you want to adjust, and that's the one that will be affected. The same way that you use an element of the array when you query the inventory amount on line 44 of your main function.

THANK YOU very much for the advise. THe problem is when I try my function I am getting 3 errors and the program wont compile. Here is the updated code (i will try the validation to the class Inventory when completed as suggested)

I renamed alot of the variables etc throughout since last post.

code for Profit.h:

//Specification file for the InventoryItem class.
#ifndef PROFIT_H
#define PROFIT_H
class Profit
{
private: 
	double itemPrice;		//cost of item
	double profitRate;		//profit percentage mark up
public:
	//used to get price from inventory class and add 30 percent profit
	Profit(double profitPrice, double profit = 0.3)
	{ itemPrice = profitPrice;
	profitRate = profit; }

	//get itemPrice
	double getItemPrice() const
	{ return itemPrice; }

	//get profit rate
	double getProfitRate() const
	{ return profitRate; }

	//get unit price by multiple profit percentage to unit cost
	double getProfit() const
	{ return (itemPrice * profitRate); }

	//get the new total unit price with 30% markup for profit
	double getTotalUnitPrice() const
	{ return (itemPrice + getProfit()); }
};
#endif

COde for Tax.h

//Specification file for the tax clase
#ifndef TAX_H
#define TAX_H


//Tax class declaration
class Tax
{
private: 
	double itemCost;		//cost of the item
	double taxRate;			//sales tax rate
	

public:
	//pull user input to get itemCost with tax rate 6%
	Tax(double subTotal, double rate = 0.06)
	{ itemCost = subTotal;
	taxRate = rate; }

	//get Item cost return
	double getItemCost() const
	{ return itemCost; }

	//get tax rate
	double getTaxRate() const
	{ return taxRate; }
	
	//get tax times itemCost
	double getTax() const
	{ return (itemCost * taxRate); }

	//get subtotal
	double getTotal() const 
	{ return (itemCost + getTax()); }
};
#endif

code for inventory class:

//Specification file for the InventoryItem class.

#ifndef INVENTORYITEM_H
#define INVENTORYITEM_H
#include <cstring>       //needed for strlen and strcpy

//constant for description's default size
const int DEFAULT_SIZE = 51;

//InventoryItem class declaration
class InventoryItem
{
private:
    char *description;      //item description
    double cost;            //item cost
    double units;           //Number of units on hand

// Private member function.
void InventoryItem::createDescription(int size, char *value)
{
    // Allocate the default amount of memory for description.
    description = new char [size+1];
        
    // Store a value in the memory.
    strcpy(description, value);
}
 
public:
	//constructor #1
	InventoryItem()
	{//store an empty string in the description attribute.
		createDescription(DEFAULT_SIZE, "");
		//initialize cost and units.
		cost = 0.0;
		units = 0; }
	
	//constrcutor #2
	InventoryItem(char *desc)
	{//allocate memory and store the description.
        createDescription(strlen(desc), desc);
        //initialize cost and units.
        cost = 0.0;
        units = 0; }

    //constructor #3
    InventoryItem(char *desc, double c, double u)
    {//allocate memory and store the description.
        createDescription(strlen(desc), desc);
        //assign values to cost and units.
        cost = c;
        units = u; }

        //Destructor
        ~InventoryItem()
        { delete [] description; }

        //Mutator functions
        void setDescription(char *d)
        { strcpy(description, d); }

        void setCost(double c)
        { cost = c; }

		void setUnits(double u)
        { units = u; }

        //Accessor functions

        const char *getDescription() const
        { return description; }

        double getCost() const
        { return cost; }

		
        double getUnits(double qtySelected) 
		{ units -= qtySelected;
		  return units; }

};
#endif

code for the CPP

//This program demonstrates a class with a destructor
#include <iostream>
#include <iomanip>
#include "Profit.h"
#include "Tax.h"
#include "InventoryItem.h"
using namespace std;



int main()

{
	int numSelected;			//to hold number selected
	double qtySelected;			//to hold number of items ordered
	char again;					//to hold yes or no answer
	double profitPrice;			//to hold unit price amount for profit class
	double subTotal;			//to hold sub total price for tax class
    const int NUM_ITEMS = 5;	//

	//array of inventory items
    InventoryItem inventory[] = {

        InventoryItem("Hammer", 6.95, 12),
        InventoryItem("Wrench", 8.75, 20),
        InventoryItem("Pliers", 3.75, 10),
        InventoryItem("Ratchet", 7.95, 14),
        InventoryItem("Screwdriver", 2.50, 22) };
//do loop for program to function

		
do
{
	//set numeric output formatting
	cout << fixed << showpoint << setprecision(2);

	//header to display title of list of inventory
	cout << "Here is a list of our current inventory" << endl;
	cout << " " << endl;
	
	//table format
	cout << setw(7) << "Item Number" <<
    cout << setw(14) << "Description"
		 << setw(8) << "Cost" << setw(8)
		 <<setw(17) << "Units on Hand\n";
	cout << "------------------------------------------------------------\n";

	

	
	//for loop display conents of array into table format
     for (int i = 0; i < NUM_ITEMS; i++)
	 {
		cout << setw(7) << i;
		cout << setw(21) << inventory[i].getDescription();
		cout << setw(10) << "$" << inventory[i].getCost();
		cout << setw(8) << inventory[i].getUnits() << endl;
	 }

	 cout << "" << endl;			//spacer
	 cout << "" << endl;			//spacer

	 //prompt user to input inventory number purchase
	 cout << "Please enter the item number you wish to purchase: "; 
	 cin >> numSelected;

	 //validation loop to ensure number is valid
	 while((numSelected < 0) || (numSelected > 4))
	 {
		 cout << "Please enter an inventory item number 0-4: ";
		 cin >> numSelected;
	 }

	 //prompt user for quantity of selection
	 cout << "Please enter the quantity you wish to purchase: ";
	 cin >> qtySelected;

	 //validation loop to ensure number is valid
	 while(qtySelected > inventory[numSelected].getUnits())
	 {
		 cout << "Please enter quantity less than or equal to " << inventory[numSelected].getUnits() << " units: ";
		 cin >> qtySelected;
	 }
	 
	 //ensure a reference of InventoryItem object is selected to profit class
	 profitPrice = inventory[numSelected].getCost();
	
	 cout << " " << endl;			//spacer


	 //display subtotal, tax, and total
	 cout << "Here is the bill: " << endl;
	 cout << " " << endl;			//spacer

	//create a sale object for this transaction
	 //specify the item cost, but use the default
	 //tax rate of 6 percent
	 Profit itemSale2(profitPrice);
	 subTotal = itemSale2.getTotalUnitPrice() * qtySelected;
	 
	 cout << "Subtotal:\t $" << subTotal << endl;
	 //create a price object for this transaction for the tax class
	 //specify the subtotal
	 //subTotalCost = subTotal;
	 Tax itemSale(subTotal);

	 //display results
	 
	 cout << "Sales tax:\t $" << itemSale.getTax() << endl;
	 cout << "Total:\t\t $" << itemSale.getTotal() << endl;

	 //prompt user if another purchase is to be made
	 cout << "Do you want to make another purchase? ";
	 cin >> again;
	 cout << " " << endl;
}
//while loop to control if another purchase is going to be made
while (again == 'Y' || again == 'y');

return 0;
}

/*
void changeQty(InventoryItem inventory, double qtySelected, double numSelected)
{
	if (numSelected == 1)
		inventory[1].getUnits() == 1;
	else
		inventory[1].getunits();

}
*/

ok here are the error messages I get. They all resolve back to my cpp stating that getUnits doesnt seem to be valid sinc my getUnits method can take form of 0. Any suggestions???

ERRORS:
Error 3 error C2660: 'InventoryItem::getUnits' : function does not take 0 arguments c:\cashregister.cpp 57

Error 4 error C2660: 'InventoryItem::getUnits' : function does not take 0 arguments c:\cashregister.cpp 79

Error 5 fatal error C1903: unable to recover from previous error(s); stopping compilation c:\cashregister.cpp 79

Member Avatar for r.stiltskin

There are only 2 errors and they are both caused by the same thing. (And the error messages tell you what is wrong. They say that on line 57 and on line 79 of cashregister.cpp, you are calling the getUnits function with NO arguments and that function, as you have changed it, doesn't take NO arguments. It now takes 1 argument. (You do realize, don't you, that an "argument" is what you put inside the parentheses when you call a function.)

The problem is that you changed the getUnits function, instead of adding an additional, new function to your inventoryItem class. Change getUnits() back to its original form and write a new function with the signature double recordSale( double qtySold ) as I described above.

Edit: by the way, that new function would be a "mutator" function, since it changes (mutates) the value of one of the class member variables.

There are only 2 errors and they are both caused by the same thing. (And the error messages tell you what is wrong. They say that on line 57 and on line 79 of cashregister.cpp, you are calling the getUnits function with NO arguments and that function, as you have changed it, doesn't take NO arguments. It now takes 1 argument. (You do realize, don't you, that an "argument" is what you put inside the parentheses when you call a function.)

The problem is that you changed the getUnits function, instead of adding an additional, new function to your inventoryItem class. Change getUnits() back to its original form and write a new function with the signature double recordSale( double qtySold ) as I described above.

Edit: by the way, that new function would be a "mutator" function, since it changes (mutates) the value of one of the class member variables.

GOT IT!!!! THANK YOU SOOOOOOO MUCH. This has been causing me the biggest headache ever. Now all I have to do is change my validation to functions in inventory class and I am set. Thank you again for your patience and help. YOu saved me big time and I can now go to bed and sleep sound knowing my program works. Thank you again.

#
double getItemPrice() const
#
{ return itemPrice; }

I am working on the same program i dont copy, i just want to understand...i understand mostly everything but what is that returning too?

I am constantly amazed and disapointed by the number of people that respond to programming questions with some variation on the theme of:

you are stupid and need to do more research before you ask a question

Or

You just want someone to do your homeowrk for you because you are lazy.

Can't you just answer or help and if you don't want to do that, move along and don't post anything? It is a horrible thing to do, especially when someone has been working on a problem for two or three weeks and just can't figure it out. Sometimes a learner just needs a little help.

And you posted that comment to a dead, five year old thread, with absolutely no relevance to the issue you are complaing about, for why?

The post you are commenting to seems to have been someone stuck with their homework who posted code, asked questions, got help, was happy. So where's the problem with that again?

Anyway, what this thread does show is that if someone asking for help abides by the rules here which clearly state:

provide evidence of having done some work yourself if posting questions from school or work assignments

then they tend to get the help they are asking for. However, if someone just wants DaniWeb members to do their homework for them then that ain't going to happen. Simple as. If, as the person asking for the help, you don't want to abide by the rules on DaniWeb then, to quote your own words, move along.

... have things ever got so slack around Dani's place ... in the last several weeks ?

So many ... dead threads ... now ... being resuscitated?

There comes a time when someone else has reason to look at that "dead" thread and to them it is a current topic of interest. Why should a new thread be created when there is already a perfectly good one in existance?
That would be like building a new house because the one I have is old.

So many ... dead threads ... now ... being resuscitated?

happens every new semester when programming courses start in certain countries where the majority of kids aren't interested in learning, only in getting the paperwork so they can get hired by firms that then sell them to other companies looking to outsource their programming departments to India.

Dani ...

I think we have a 'malicious stalker' haunting your normally nice and friendly web space ?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.