Issue With My School Assignment on Classes - c++

So I have an assignment due in my C++ class on classes, and I'm having some trouble. Here is the description of the assignment:
Programming Challenge 7 on page 499 of your text asks you to design and Inventory Class that can hold information for an item in a retail store's inventory. You are given the code for the creation of the class along with code for the implementation of the functions. Demonstrate the class by writing a simple program that uses it. This program should demonstrate that each function works correctly. Submit your .cpp file using the link provided.
And here are the contents of the file sent (it's quite lengthy):
// Chapter 7---Files for Programming Challenge 13---Inventory Class
// This is the inventory.h file.
// It contains the Inventory class declaration.
#ifndef INVENTORY_H
#define INVENTORY_H
class Inventory
{
private:
int itemNumber;
int quantity;
double cost;
double totalCost;
public:
// Default constructor
Inventory()
{ itemNumber = quantity = cost = totalCost = 0; }
// Overloaded constructor
Inventory(int, int, double); // Defined in Inventory.cpp
// Mutators (i.e., "set" functions) defined in Inventory.cpp
void setItemNumber(int);
void setQuantity(int);
void setCost(double);
// setTotalCost calculates the total cost
// and stores the result in the totalCost member
void setTotalCost()
{ totalCost = cost * quantity; }
// Accessors (i.e., "get" functions)
int getItemNumber()
{ return itemNumber; }
int getQuantity()
{ return quantity; }
double getCost()
{ return cost; }
double getTotalCost()
{ return totalCost; }
// Input validation functions
bool validInt(int);
bool validFloat(double);
};
#endif
// This is the inventory.cpp file.
// It contains the Inventory class function definitions.
#include <iostream>
#include "Inventory.h"
using namespace std;
//************************************************************
// Overloaded constructor
// Accepts arguments to be stored in each member variable.
//************************************************************
Inventory::Inventory(int in, int q, double c)
{
setItemNumber(in);
setQuantity(q);
setCost(c);
setTotalCost();
}
//************************************************************
// setItemNumber accepts an argument to be stored in item number.
//************************************************************
void Inventory::setItemNumber(int in)
{
while (!validInt(in))
{
cout << "Item Number must be positive. Please re-enter: ";
cin >> in;
}
itemNumber = in;
}
//************************************************************
// setQuantity accepts an argument to be stored in quantity.
//************************************************************
void Inventory::setQuantity(int q)
{
while (!validInt(q))
{
cout << "Quantity must be positive. Please re-enter: ";
cin >> q;
}
quantity = q;
}
//************************************************************
// setCost accepts an argument to be stored in cost.
//************************************************************
void Inventory::setCost(double c)
{
while (!validInt(c))
{
cout << "Cost must be positive. Please re-enter: ";
cin >> c;
}
cost = c;
}
//************************************************************
// The validInt member tests its integer argument to see
// if it is negative. If the argument is negative, the function
// returns false. Otherwise, the function returns true.
//************************************************************
bool Inventory::validInt(int value)
{
if (value < 0) // the value is negative so it is NOT valid
return false;
else // the integer value is valid
return true;
}
//************************************************************
// The validFloat member tests its floating-point argument to see
// if it is negative. If the argument is negative, the function
// returns false. Otherwise, the function returns true.
//************************************************************
bool Inventory::validFloat(double value)
{
if (value < 0) // the value is negative so it is NOT valid
return false;
else // the floating-point value is valid
return true;
}
I'm just not sure how to use this information to make a program that demonstrates the class, and it could be as simple as me not saving the file the correct way

Just write a main function which instantiates an Inventory object and calls each of its methods in a meaningful way. This isn't a puzzle, just find a way to call the functions that makes sense to you.

Related

Verifying a pincode, ATM program

I'm writing a program that simulates an ATM and I'm having problems with the account arrays in the program. The account arrays hold the account number, pin code, and account balance. The very first function in the code allows the user to log in with their pin and account number, but I'm having issues comparing the user input to the account array:
#include <iostream>
#include <string>
using namespace std;
class Account
{
private: int accountNum;
int accountPin;
double accountBalance;
int setPin();
int setAccountNum();
public: Account();
Account(int, string, double);
double setAccountBalance(int) ;
int getAccountNum();
int confirmPin(string) ;
double updateBalance(double) ;
};
void confirmPin(string accountPin, int accountNum)
{
//confirm pin segment
// returns true or false value, allows access to account balance information
}
int main () {
Account account[3] =
{
{123, "abc123", 100.00}, {456, "def456", 50.00},{789, "ghi789", 500.63}
};
int option;
cout << "LOGIN\nEnter Account#: "<< endl;
cin >> accountNum;
cout << "Enter password";
cin >> accountPin;
//confirm pin function
I coded as much as I could at the moment. I have no clue where to start in terms of comparing the input to the account info. Thanks in advance for any help!
Here are some examples to get you started.
Overload equality comparison
class Account
{
//...
public:
bool operator==(const Account& a) const
{
if (accountNum != a.accountNum) return accountNum < a.accountNum;
else
{
if (accountPin != a.accountPin) return accountPin < a.accountPin;
else
{
double difference = abs(accountBalance - a.accountBalance);
if (difference < 1.0E-6) return true;
}
return false;
}
};
This allows you to input one instance and compare to another instance for equality.
Create Comparison Function
Add a method to your class that compares account numbers:
class Account
{
//...
public:
bool is_equal_account_number(const Account& a) const
{
return accountNum == a.accountNum;
}
};
The above method allows you to compare only the account numbers. This may be useful since duplicate account numbers are probably not allowed.
Compare By Value
Another example is to write a method that will compare the account number with a given account number.
class Account
{
//...
public:
bool same_account_number(const int acct_num) const
{ return accountNum == acctnum);
};
The above are some examples of comparing accounts. There are others, like employing getter functions and comparing those values.

class pointer method crashing program

I am trying to make a program that has two account balances, one for a go-card the other for a bank account. I have made a class for each, however when I try to call the debit method in the go-card class via a class pointer, my program crashes (it compiles with no errors).
The GoCardAccount.cpp file:
#include <cstdio>
#include "GoCardAccount.hpp"
#include "BankAccount.hpp"
GoCardAccount::GoCardAccount(long initialamount, BankAccount(ba)) {
balance = initialamount;
}
bool GoCardAccount::trip(long amount) {
LOW_LIMIT = 1000;
TOP_UP = 5000;
if(balance >= amount) {
balance -= amount;
if(balance < LOW_LIMIT) {
if(ba->debit(TOP_UP)) {
printf("Balance fallen below minimum, "
"topped up $50 to go card account.\n");
balance += TOP_UP;
return true;
}
else {
printf("Your balance has gone below minimum amount, however "
"there are insufficient funds in bank account to top up.\n");
return true;
}
}
}
else {
return false;
}
}
long GoCardAccount::getBalance() {
return balance;
}
GoCardAccount.hpp file:
class BankAccount;
class GoCardAccount {
long balance;
BankAccount *ba;
long LOW_LIMIT;
long TOP_UP;
public:
GoCardAccount(long amount, BankAccount(ba));
bool trip(long amount);
long getBalance();
};
The debit method from BankAccount.cpp:
bool BankAccount::debit(long amount1) {
if(amount1 >=0 && amount1 <= balance) {
balance -= amount1;
return true;
}
else {
return false;
}
}
The start of the main function where I initialise the classes:
int main(void) {
long startamount;
long gocardamount;
printf("Input initial bank balance: \n");
scanf("%ld", &startamount);
BankAccount ba(startamount);
printf("Input initial Go-Card balance: \n");
scanf("%ld", &gocardamount);
GoCardAccount gca(gocardamount, ba);
}
For first let's talk about your constructor of class GoCardAccount, because there is a term used by Scott Meyers in Effective STL (2001) book, which is the most vexing parse:
GoCardAccount(long amount, BankAccount(ba));
The code snippet above will declare a constructor which takes two parameters:
The long amount parameter is named amount, and it's type is long. This is fine.
The BankAccount(ba) parameter is named ba, and it's type is BankAccount, because the parentheses around ba are superfluous and are ignored.
So, the declaration above is same as:
GoCardAccount(long amount, BankAccount ba);
This isn't what you want, because the second parameter will take a BankAccount instance by value and you need a pointer to it. So, you have to change it to:
GoCardAccount(long amount, BankAccount* ba);
Change its definition as well and initialize your BankAccount* ba member as follows (or use the member initializer list):
GoCardAccount::GoCardAccount(long initialamount, BankAccount* ba_ptr) {
balance = initialamount;
ba = ba_ptr;
}
Now you are trying to call ba method, but BankAccount *ba; is not even itinialized.
You have to pass a pointer on BankAccount to GoCardAccount ctor. So change this line (in main)
GoCardAccount gca(gocardamount, ba);
to
GoCardAccount gca(gocardamount, &ba);
and in GoCardAccount (GoCardAccount.cpp) change ctor from
GoCardAccount::GoCardAccount(long initialamount, BankAccount(ba))
{
balance = initialamount;
}
to
GoCardAccount::GoCardAccount(long initialamount, BankAccount * pba) :
balance (initialamount), ba(pba) {}
The argument
BankAccount(ba)
won't store argument passed to ctor to ba, it means that argument passed in function call, which will be placed on stack, will has identifier ba.
You should use different name than member variable
It has to be pointer (in your case)
In member initialize list you have to assign this value to member variable
Example
GoCardAccount::GoCardAccount(long initialamount, BankAccount * pba) : balance (initialamount), ba(pba) {}

C++ Boolean statement errors (I think)

This program is supposed to ask for an integer, if you want to add or subtract, then another integer, then do the math, but it declares both subtraction and addition as false inputs and i think there are errors in my boolean. Any help is appreciated.
/***********************************************************
Program Name: Simple Math Calculator
Program Author: Kyle NoCompile
Date Created: 9/12/16
Program Description:
This program performs simple arithmetic calculations.
The user enters numbers and the math operation to
perform on those numbers. The program will then display
the result of the operation.
Modified Date:
Modified Description:
***********************************************************/
#include <iostream>
using namespace std;
// Function prototypes:
void showWelcome();
int getUserIntegerInput();
char getMathChoice();
int getInteger(bool);
bool validateMathChoice(char choice);
int doAddition(int int1, int int2);
int doSubtraction(int int1, int int2);
int doMath(int firstInt, int secondInt, char mathFunc);
int showResult();
// This is the main function (where the program begins)
int main()
{
// Variables to hold local data
int firstNum;
int secondNum;
int mathChoice;
int result;
// Call the showWelcome() function
void showWelcome();
// Call the getInteger() function (for the first integer)
// and store the result in the "firstNum" variable
firstNum = getInteger(true);
// Call the getMathChoice() function and store result in "mathChoice" variable
mathChoice = getMathChoice();
// Call validateMathChoice() function, passing it the user's math choice
// and using the return value to decide what to do next
if (validateMathChoice() = true)
{
// Call the getInteger() function (for the second and subsequent integers)
// and store the result in the "secondNum" variable
secondNum = getInteger(false);
// Call the doMath() function and pass it all of the user input
// and store the return value in the "result" variable.
int result = doMath(firstNum,secondNum,mathChoice);
// Call the showResult() function to show the result
int showResult(int result);
}
else
{
// If the user chose an invalid math function...
cout<<"Not a valid math choice"<<endl;
}
return 0;
}
// This function shows a nice welcome message
void showWelcome()
{
cout<<"******************************************"<<endl;
cout<<"Welcome to the simple calculator program!"<<endl;
cout<<"This program will do simple addition and"<<endl;
cout<<"subtraction. Math is fun, so enjoy!"<<endl;
cout<<"******************************************"<<endl;
}
// This function gets integer input from the user
int getUserIntegerInput()
{
int input;
cin>>input;
return input;
}
// This function asks the user for a math function
// and returns the user's input
char getMathChoice()
{
char choice;
cout<<endl<<"Please select a math function to perform (\"+\" = Addition, \"-\" = Subtraction): ";
cin>>choice;
return choice;
}
// this function asks the user for either the first integer
// or the second and returns the user's input
int getInteger(bool firstNum)
{
cout<<endl<<"Please enter the ";
// if the "firstNumber" variable is true, then this
// is the first number being collected
if (firstNum)
{
cout<<"first ";
}
// Otherwise, it's the second number being collected
else
{
cout<<"second ";
}
cout<<"integer: ";
// Call the getUserIntegerInput() function and return the return value from it
return getUserIntegerInput();
}
// This function validates the user's match function choice
// by returning a true for valid, and a false for invalid
bool validateMathChoice(char choice)
{
if (choice == '+' || choice == '-')
{
return true;
}
else
{
return false;
}
}
// This function adds two integers
int doAddition(int firstInt,int secondInt)
{
return firstInt + secondInt;
};
// This function subtracts the second integer
// parameter from the first integer parameter
int doSubtraction(int firstInt, int secondInt)
{
return firstInt - secondInt;
};
// This function determines the result of the math
// operation requested by the user
int doMath(int firstInt, int secondInt, char mathFunc)
{
// Initialize result to zero (0)
int result = 0;
// If the math function is a "+", then call the
// doAddition() function and store the return
// value in the "result" variable
if (mathFunc = '+')
{
result = doAddition(firstInt, secondInt);
return result;
}
// If the math function is a "-", then call the
// doSubtraction() function and store the return
// value in the "result" variable
else (mathFunc = '-');
{
result = doSubtraction(firstInt, secondInt);
return result;
}
return result;
}
// This function displays the result of a math operation
int showResult(int result)
{
cout<<endl<<"The result is "<<result<<endl;
}

Getting wrong output. Garbage value

Problem is, on execution, the value of roundCost I'm getting is
something like -1220673834. I post the entire program because I'm not
sure where I'm going wrong.
Note: I was asked to take all variables as double type and later,
roundCost should be of type int. So I used type conversion there.
#include<iostream>
using namespace std;
class Restaurant{
private:
double tip, tax,totalCost,mealCost, tipPercent, taxPercent;
int roundCost;
public:
int tipCalc(double)
{
tip=mealCost*(tipPercent/100);
return tip;
}
int taxCalc(double)
{
tax=mealCost*(taxPercent/100);
return tax;
}
int totalCost1()
{
totalCost=mealCost+tip+tax;
return totalCost;
}
int roundCost1(double)
{
roundCost=(int)totalCost;
return roundCost;
}
}; // class ends
int main()
{
double mealCost, tipPercent, taxPercent, totalCost;
int roundCost;
Restaurant ob1;
cout<<"\n Enter mealCost \n";
cin>>mealCost;
cout<<"\n Enter mealtipPercent \n";
cin>>tipPercent;
cout<<"\n Enter mealtaxPercent \n";
cin>>taxPercent;
ob1.tipCalc(tipPercent);
ob1.taxCalc(taxPercent);
ob1.totalCost1();
ob1.roundCost1(totalCost);
cout<<"\n Round of cost is "<<roundCost<<endl;
return 0;
}
One thing you seem to be missing is that variables in your class have a different scope then variables in your main. You set the mealcost in your main from cin but you never passed this variable to the class. I changed this to be done using a constructor that sets the meal cost on creation. In every class you make you should always add a constructor. Also, you should be naming the variables your passing to functions and then using the same name in the function. For example in the tax percent function i pass double t, t is the percent, we then use t in the calculation. Your round cost variable was also private so you needed to output it via a function.
Also int functions will return a value, if you are using this type of function you should be assigning the return variable to something, but since you are just setting things in your class you can use void functions for most. The only time you use a value in the main is in the roundcost so this one is good to have it return a value. As it is int (which i assumed you wanted) it will get no decimal points and it will simply cut off any decimals in the total cost (ie 75.75 would become 75).
#include<iostream>
using namespace std;
class Restaurant{
private:
double tip, tax,totalCost,mealCost;
int roundCost;
public:
Restaurant (double m)
{
mealCost = m;
}
void tipCalc(double t)
{
tip=mealCost*(t/100.0);
}
void taxCalc(double t)
{
tax=mealCost*(t/100.0);
}
void totalCost1()
{
totalCost=mealCost+tip+tax;
}
int roundCost1()
{
roundCost=(int)totalCost;
return roundCost;
}
}; // class ends
int main()
{
double mealCost, tipPercent, taxPercent, totalCost;
int roundCost;
cout<<"\n Enter mealCost \n";
cin>>mealCost;
Restaurant ob1(mealCost);
cout<<"\n Enter mealtipPercent \n";
cin>>tipPercent;
cout<<"\n Enter mealtaxPercent \n";
cin>>taxPercent;
ob1.tipCalc(tipPercent);
ob1.taxCalc(taxPercent);
ob1.totalCost1();
cout<<"\n Round of cost is "<<ob1.roundCost1()<<endl;
return 0;
}
Try to do a bit more research next time by using a debugger, outputting cout statements regularly and searching for the errors you find but this will give you a working code this time.

Not understanding the error message I'm getting

I doing a freind function program according to this book I have and I did a little of my own code to the program. I puzzle because I get this error message that the "room_num" is undeclared and intellisense identifier "room_num" is undefine. I need help in understanding why this is happen and how to fix it. Here is the code I have been working on for the passed three weeks.
#include "stdafx.h"
#include <iostream>
#include <iomanip>
using namespace std;
class HotelRoom
{
friend int Transfer( HotelRoom&, int);
private:
int room_num;
int transroom_num;
int room_cap;
int occup_stat;
double daily_rt;
public:
HotelRoom(int room, int roomcap, int occup, int transroom, double rate = 89.00);
~HotelRoom();
int Display_Number(); //Displays room number and add the method Display_Guest()
int Get_Capacity();
int Get_Status();
double Get_Rate();
int Change_Status(int);
double Change_Rate(double);
void Display_Guest();
};
HotelRoom::~HotelRoom()
{
cout << endl<<endl;
cout << "Guest in room "<<room_num << " has checked out." <<endl;
}
int HotelRoom::Display_Number()
{
return room_num;
}
int HotelRoom::Get_Capacity()
{
return room_cap;
}
int HotelRoom::Get_Status()
{
return occup_stat;
}
int HotelRoom::Change_Status(int occup)
{
occup_stat = occup;
if (occup > room_cap)
{
return -1;
}
else
return occup_stat;
}
double HotelRoom::Get_Rate()
{
return daily_rt;
}
double HotelRoom::Change_Rate(double rate)
{
daily_rt = rate;
return daily_rt;
}
int Transfer(HotelRoom& room_r1, int transroom)
{
//if guest transfers to different hotel room, room is vacant and transroom is now occupied
room_r1.room_num = room_r1.transroom_num;
return room_num;
}
int main()
{
cout<< setprecision(2)
<<setiosflags(ios::fixed)
<<setiosflags(ios::showpoint);
int room = 0;
int roomcap = 4;
int transroom;
int occup;
double rate = 89.00;
cout<<"\nEnter the room number: "<<endl;
cin>>room;
cout<<"\nEnter the amount of guest to occupy this room: "<<endl;
cin>>occup;
cout<<"\nThe guest has decided to transfer rooms"<<endl;
cout<<"\nEnter the room to transfer the guest to"<<endl;
cin>>transroom;
HotelRoom room1(room,roomcap, occup, transroom, rate ); //initialize the object
if (room1.Change_Status(occup) == -1)
{
cout<<"You have exceeded the room capacity"<<endl;
}
else
{
cout <<"\nThe room number is ";
room1.Display_Number();
cout<<"."<<endl;
cout<<"\nThe name of the primary guest is ";
room1.Display_Guest();
cout <<"."<<endl;
cout<<"\nThe number of guest in the room is "<<room1.Change_Status(occup)<<"." <<endl;
cout<<"\nThe daily rate for room "<<room<< " is "<<room1.Get_Rate()<<"."<<endl<<endl;
cout<<"\nYou have tranferred the guest from room"<<room1.Display_Number()<<"to" <<Transfer(room1,transroom)<<endl;
}
cout<<"\nRoom ";
room1.Display_Number();
cout<<" is vacant."<<endl;
system("PAUSE");
return 0;
}
The function Transfer is not a method of HotelRoom, still you are trying to access room_num in it as if it was. You need to specify which room_num of which HotelRoom instance you mean. Probably you meant return room_r1.room_num instead of return room_num.
Also in your Transfer function you never use the parameter transroom, instead you are using a transroom_num from room_r1. This is probably not what you want.
Finally you haven't implemented the constructor and DisplayRoom of HotelRoom. You should create a stubs, which do nothing or print warnings as long as you haven't implemented the methods properly, so you can at least compile and link the code.
Since you are a beginner I would just stick with member functions and class private variables until you get better at it.
As far as the error message, my guess is that inside the function you are using room_num does not have access to the private parts of the HotelRoom class. Notice I said guess, that's because you should copy and paste the text on the output window here so we can see what exactly is happening.
First, you have to identify that room_num is class member variable.
int Transfer(HotelRoom& room_r1, int transroom)
{
room_r1.room_num = room_r1.transroom_num;
//because room_num is not non class member variable, you have to write like below.
return room_r1.room_num;
//return room_num;
}
Secondly, you did not write definition HotelRoom::HotelRoom(int,int,int,int,double), HotelRoom::Display_Guest(void). So you have to write this constructor and function for avoiding error LNK2019.