Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I am writing this program for my class and have run into an issue. There are no errors but when I try to compile (compiling with g++), the program stops outputting to console after the line "Stuart placing order.\n". I know \n doesn't flush the output, so I tried using flush but that didn't work (maybe I did it wrong?). What do I need to do to allow the program to show the full output in console? I'm not really sure where I'm going wrong as I've been trying to figure out the problem for a while now. I'm still relatively new so I apologize if this is a simple fix. Thank you in advance.
output:
Kevin placing order.
Invalid input [Iron Goddess].
Not serving requested drinks. Drink order ignored.
Order Detail:
Kevin
Date: 3/2/2021
Phone: 123-456-0000
Total Balance: $21.75
Ordered Drinks: 4
Balance: $39.279
Discounted Balance: $37.315
Stuart placing order.
main
#include <string>
#include "Order.h"
#include <iostream>
using namespace std;
int main()
{
const Account Stuart("Stuart", "Owner");
Account Kevin("Kevin", "VIP");
Account Bob("Bob", "");
cout << "Kevin placing order.\n";
BobaOrder K("Kevin", 3, 2, 2021, "123-456-0000", 10.4, "Bar Pa Tea", 0.0);
try
{
K.addDrink("Matcha Lemonade", 1, true);
K.addDrink("Lemon Green Tea", 1, false);
K.addDrink("Brown Sugar Oolong Tea", 2, false);
K.addDrink("Iron Goddess", 1, false);
}
catch(InvalidInput& WrongDrink)
{
WrongDrink.cause();
cout << "Not serving requested drinks. Drink order ignored.\n";
}
cout.precision(5);
K.printReceipt();
cout << "Balance: $" << K.calcBalance() << endl;
cout << "Discounted Balance: $" << applyDiscount(&K, &Kevin) << endl << endl;
cout << "Stuart placing order.\n";
FoodOrder S("Stuart", 3, 2, 2021, "123-456-1111", 25.5, "Trauts Steak House", 0.0);
try
{
S.addFood("Bone-in Ribeye", 2, true);
S.addFood("Grilled Salmon", 1, false);
S.addFood("Beyond Meat Burger", 3, true);
}
catch(InvalidInput& WrongFood)
{
WrongFood.cause();
cout << "Not serving requested food. Food order ignored.\n";
}
S.printReceipt();
cout << "Balance: $" << S.calcBalance() << endl;
cout << "Discounted Balance: $" << applyDiscount(&S, &Stuart) << endl << endl;
return 0;
}
cpp file
#include "Order.h"
#include <iostream>
using namespace std;
int DeliveryOrder::orderCount;
const float DeliveryOrder::taxRate = 0.0887;
const float DeliveryOrder::deliveryRate = 1.5;
int BobaOrder::drinksCount;
int FoodOrder::foodCount;
DeliveryOrder::DeliveryOrder(string name, int month, int day, int year, string phone, float miles, float balance = 0.0)
{
DeliveryOrder::name = name;
DeliveryOrder::month = month;
DeliveryOrder::day = day;
DeliveryOrder::year = year;
DeliveryOrder::phone = phone;
DeliveryOrder::miles = miles;
DeliveryOrder::balance = balance;
orderCount++;
}
DeliveryOrder::~DeliveryOrder()
{
cout << "DeliveryOrder destroyed.\n";
}
void DeliveryOrder::printReceipt() const
{
cout << "Order Detail:" << "\n";
cout << "\t" << name << "\n";
cout << "\tDate: " << month << "/" << day << "/" << year << "\n";
cout << "\tPhone: " << phone << "\n";
cout << "\tTotal Balance: $" << balance << "\n";
}
float DeliveryOrder::calcBalance()
{
balance = balance * (1 + taxRate) + miles * deliveryRate;
return balance;
}
float DeliveryOrder::getBalance() const
{
return balance;
}
int DeliveryOrder::getOrderCount()
{
return orderCount;
}
BobaOrder::BobaOrder(string name, int month, int day, int year, string phone, float miles, string shopName, float balance)
:DeliveryOrder(name, month, day, year, phone, miles, balance)
{
BobaOrder::shopName = shopName;
}
BobaOrder::~BobaOrder()
{
cout << "BobaOrder destroyed.\n";
}
void BobaOrder::printReceipt() const
{
DeliveryOrder::printReceipt();
cout << "\tOrdered Drinks: " << drinksCount << endl;
}
float BobaOrder::VIPdiscount() const
{
float discount;
if (drinksCount > 10){discount = 0.85;}
else
{
if (drinksCount > 5){discount = 0.9;}
else
{
if (drinksCount > 2){discount = 0.95;}
else
{
if(drinksCount <= 2){discount = 1;}
}
}
}
return discount;
}
void BobaOrder::addDrink(string drinkName, int sameDrink = 1, bool boba=true)
{
if (drinkName == "Matcha Lemonade"){balance = balance + 5.5 * sameDrink;}
else
{
if (drinkName == "Brown Sugar Oolong Tea"){balance = balance + 5 * sameDrink;}
else
{
if (drinkName == "Lemon Green Tea"){balance = balance + 5.25 * sameDrink;}
else
{
throw InvalidInput(drinkName);
}
}
}
if (boba==true){balance = balance + 1 * sameDrink;}
drinksCount = drinksCount + sameDrink;
}
FoodOrder::FoodOrder(string name, int month, int day, int year, string phone, float miles, string restaurantName, float balance)
:DeliveryOrder(name, month, day, year, phone, miles, balance)
{
FoodOrder::restaurantName = restaurantName;
}
FoodOrder::~FoodOrder()
{
cout << "FoodOrder destroyed.\n";
}
void FoodOrder::printReceipt() const
{
FoodOrder::printReceipt();
cout << "\tOrdered Foods: " << foodCount << endl;
}
float FoodOrder::VIPdiscount() const
{
float discount;
if (balance > 50){discount = 0.85;}
else
{
if (balance > 30){discount = 0.9;}
else
{
if (balance > 20){discount = 0.95;}
else
{
if(balance <= 20){discount = 1;}
}
}
}
return discount;
}
void FoodOrder::addFood(string foodName, int sides = 0, bool soup=false)
{
if (foodName == "Bone-in Ribeye"){balance = 32 + balance;}
else
{
if (foodName == "Rack of Lamb"){balance = 28 + balance;}
else
{
if (foodName == "Grilled Salmon"){balance = 24 + balance;}
else
{
if (foodName == "Beyond Meat Burger"){balance = 22 + balance;}
else
{
throw InvalidInput(foodName);
}
}
}
}
if (soup==true){balance = balance + 0.5;}
balance = balance + sides * 1;
foodCount++;
}
Account::Account(string username, string status)
{
Account::username = username;
Account::status = status;
}
Account::~Account()
{
cout << "Account Removed.\n";
}
string Account::getStatus() const
{
return status;
}
float applyDiscount(DeliveryOrder *o, Account const *a)
{
float b = o->getBalance();
float v = o->VIPdiscount();
if (a->getStatus() == "Owner"){b = b * 0.1;}
else
{
if(a->getStatus() == "VIP"){b = b * v;}
}
return b;
}
h file
#ifndef ORDER_H
#define ORDER_H
#include <string>
#include <iostream>
using namespace std;
class DeliveryOrder
{
private:
string name;
int month;
int day;
int year;
string phone;
float miles;
static int orderCount;
protected:
float balance;
public:
const static float taxRate;
const static float deliveryRate;
DeliveryOrder(string, int, int, int, string, float, float);
~DeliveryOrder();
void printReceipt() const;
float calcBalance();
float getBalance() const;
static int getOrderCount();
virtual float VIPdiscount() const = 0;
};
class BobaOrder : public DeliveryOrder
{
private:
string shopName;
static int drinksCount;
public:
BobaOrder(string, int, int, int, string, float, string, float);
~BobaOrder();
void printReceipt() const;
virtual float VIPdiscount() const;
void addDrink(string, int, bool);
};
class FoodOrder : public DeliveryOrder
{
private:
string restaurantName;
static int foodCount;
public:
FoodOrder(string, int, int, int, string, float, string, float);
~FoodOrder();
void printReceipt() const;
virtual float VIPdiscount() const;
void addFood(string, int, bool);
};
class Account
{
private:
string username;
string status;
public:
Account(string username, string status);
~Account();
string getStatus() const;
};
class InvalidInput
{
private:
string message;
public:
InvalidInput(string s) : message("Invalid input [" + s + "].\n")
{};
void cause() {cout << message;}
};
float applyDiscount(DeliveryOrder*, Account const*);
#endif
Using a debugger may be new to you, but it will save you LOTS of time.
Running your program in a debugger would have shown you that your problem is here.
void FoodOrder::printReceipt() const
{
FoodOrder::printReceipt();
cout << "\tOrdered Foods: " << foodCount << endl;
}
Calling FoodOrder::printReceipt() will call FoodOrder::printReceipt(). Infinitely.
Related
I'm doing self-study C++. I tried a program from the book, that would normally allocate a few objects of two derived classes dynamically using an array of pointers. I'm however preparing for an assignment where I'm not allowed to use pointers, so I made an alternative version without pointers.
The only error it gives me is C2259 "cannot instantiate abstract class", but I'm pretty sure I have overriden all the virtual functions.
Here is the header:
#ifndef ACCTBAC_H_
#define ACCTBAC_H_
#include <iostream>
#include <string>
// Abstract Base Class
class AcctABC
{
private:
std::string fullName;
long acctNum;
double balance;
protected:
struct Formatting
{
std::ios_base::fmtflags flag;
std::streamsize pr;
};
const std::string& FullName() const { return fullName; }
long AcctNum() const { return acctNum; }
Formatting SetFormat() const;
void Restore(Formatting& f) const;
public:
AcctABC(const std::string& s = "Nullbody", long an = -1, double bal = 0.0);
void Deposit(double amt);
virtual void Withdraw(double amt) = 0; // pure virtual function
double Balance() const { return balance; };
virtual void ViewAcct() const = 0; // pure virtual function
virtual ~AcctABC() {}
};
// Brass Account Class
class Brass : public AcctABC
{
public:
Brass(const std::string& s = "Nullbody", long an = -1, double bal = 0.0) : AcctABC(s, an, bal) {}
virtual void Withdraw(double amt);
virtual void ViewAcct() const;
virtual ~Brass() {}
};
// Brass Plus Account Class
class BrassPlus : public AcctABC
{
private:
double maxLoan;
double rate;
double owesBank;
public:
BrassPlus(const std::string& s = "Nullbody", long an = -1, double bal = 0.0, double ml = 500, double r = 0.10);
BrassPlus(const Brass& ba, double ml = 500, double r = 0.1);
virtual void ViewAcct() const;
virtual void Withdraw(double amt);
void ResetMax(double m) { maxLoan = m; }
void ResetRate(double r) { rate = r; }
void ResetOwes() { owesBank = 0; }
};
#endif
the class functions:
// acctabc.cpp -- bank account class methods
#include <iostream>
#include "acctabc.h"
using std::cout;
using std::ios_base;
using std::string;
// Abstract Base Class
AcctABC::AcctABC(const string& s, long an, double bal)
{
fullName = s;
acctNum = an;
balance = bal;
}
void AcctABC::Deposit(double amt)
{
if (amt < 0)
cout << "Negative deposit not allowed; "
<< "deposit is cancelled.\n";
else
balance += amt;
}
void AcctABC::Withdraw(double amt)
{
balance -= amt;
}
// protected methods for formatting
AcctABC::Formatting AcctABC::SetFormat() const
{
// set up ###.## format
Formatting f;
f.flag = cout.setf(ios_base::fixed, ios_base::floatfield);
f.pr = cout.precision(2);
return f;
}
void AcctABC::Restore(Formatting& f) const
{
cout.setf(f.flag, ios_base::floatfield);
cout.precision(f.pr);
}
// Brass methods
void Brass::Withdraw(double amt)
{
if (amt < 0)
cout << "Withdrawal amount must be positive; "
<< "withdrawal cancelled.\n";
else if (amt <= Balance())
AcctABC::Withdraw(amt);
else
cout << "Withdrawal amount of $" << amt
<< " exceeds your balance.\n"
<< "Withdrawal cancelled.\n";
}
void Brass::ViewAcct() const
{
Formatting f = SetFormat();
cout << "Brass Client: " << FullName() << "\n";
cout << "Account Number: " << AcctNum() << "\n";
cout << "Balance: $" << Balance() << "\n";
Restore(f);
}
// BrassPlus methods
BrassPlus::BrassPlus(const string& s, long an, double bal, double ml, double r) : AcctABC(s, an, bal)
{
maxLoan = ml;
owesBank = 0.0;
rate = r;
}
void BrassPlus::ViewAcct() const
{
Formatting f = SetFormat();
cout << "BrassPlus Client: " << FullName() << "\n";
cout << "Account Number: " << AcctNum() << "\n";
cout << "Balance: $" << Balance() << "\n";
cout << "Maximum loan: $" << maxLoan << "\n";
cout << "Owed to bank: $" << owesBank << "\n";
cout.precision(3);
cout << "Loan Rate: " << 100 * rate << "%\n";
Restore(f);
}
void BrassPlus::Withdraw(double amt)
{
Formatting f = SetFormat();
double bal = Balance();
if (amt <= bal)
AcctABC::Withdraw(amt);
else if (amt <= bal + maxLoan - owesBank)
{
double advance = amt - bal;
owesBank += advance * (1.0 + rate);
cout << "Bank Advance: $" << advance << "\n";
cout << "Finance charge: $" << advance * rate << "\n";
Deposit(advance);
AcctABC::Withdraw(amt);
}
else
cout << "Credit limit exceeded. Transaction cancelled.\n";
Restore(f);
}
and the main program:
// usebrass3.cpp -- polymorphic example using an abstract base class
#include <iostream>
#include <string>
#include "acctabc.h"
#include <vector>
const int CLIENTS = 4;
int main()
{
using std::cin;
using std::cout;
using std::vector;
using std::string;
vector<AcctABC> accounts(CLIENTS);
string temp;
long tempnum;
double tempbal;
char kind;
for (int i = 0; i < CLIENTS; i++)
{
cout << "Enter client's name: ";
getline(cin, temp);
cout << "Enter client's account number: ";
cin >> tempnum;
cout << "Enter opening balance: $";
cin >> tempbal;
cout << "Enter 1 for Brass Account: ";
while (cin >> kind && (kind != '1' && kind != '2'))
cout << "Enter either 1 or 2: ";
if (kind == 1)
accounts.push_back(Brass(temp, tempnum, tempbal));
else
{
double tmax, trate;
cout << "Enter the overdraft limit: $";
cin >> tmax;
cout << "Enter the interest rate "
<< "as a decimal fraction: ";
cin >> trate;
accounts.push_back(BrassPlus(temp, tempnum, tempbal, tmax, trate));
}
while (cin.get() != '\n')
continue;
}
cout << "\n";
for (int i = 0; i < CLIENTS; i++)
{
accounts[i].ViewAcct();
cout << "\n";
}
cout << "Done.\n";
return 0;
}
Here:
vector<AcctABC> accounts(CLIENTS);
you are trying to create a vector of AcctABC with CLIENTS default constructed AcctABC elements. But you cannot have AcctABC elements when the class is abstract. You also cannot have Brass elements in a vector of AcctABCs. You need pointers when you want to store a polymorphic type in a vector.
You cannot do this
vector<AcctABC> accounts(CLIENTS);
because it will make CLIENTS number of default constructed abstract base classes. You will also lose polymorphism and induce object slicing. Instead
vector<std::unique_ptr<AcctABC>> accounts;
then for example
accounts.push_back(std::make_unique<Brass>(temp, tempnum, tempbal));
I have an issue with a class i have created. When i compiling this so occures error message. Its basically all about char* to string. Here is my class
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
class Stock //klassdekleration
{
private:
char company[30];
int shares;
double share_val;
double total_val;
void set_tot() {total_val = shares * share_val;}
public:
Stock();
Stock(const char * co, int n = 0, double pr = 0.0);
void acquire(const char * co, int n, double pr);
void buy(int num,double price);
void sell(int num, double price);
void update(double price);
void show();
void compare( Stock );
const char * returncompany();
int returnshares();
};
#endif
// class function
//------------------------------------------------------------------------------------------------------
// constructor
Stock::Stock()
{
cout << "pre constructor is called \n";
strcpy(company, "namnlöst");
shares = 0;
share_val = 0;
total_val = 0;
}
Stock::Stock(const char * co, int n, double pr)
{
cout << " Constructor that use " << co << " is called \n";
strcpy("company", co);
company[29] = '\0';
shares = n;
share_val=pr;
set_tot();
}
//---------------------------------------------------------------------------------------------------------
// andra metoddefintioner
void Stock::acquire(const char * co, int n, double pr)
{
strcpy(company, co); //trunkera co om det behövs
company[29]='\0';
if (n<0)
{
cerr << "amount of shares cant be negative "
<< "share put to 0. \n";
shares = 0;
}
else
shares = n;
share_val = pr;
set_tot();
}
void Stock::buy(int num, double price)
{
if (num < 0)
{
cerr << "Amount of bought shares cant be negative. "
<< "transaction cancelled. ";
}
else
{
shares += num;
share_val = price;
set_tot();
}
}
void Stock::sell(int num, double price)
{
if (num < 0)
{
cerr << "amount of sold shares cant be negative. "
<< "Transaction cancelled. ";
}
else if (num > shares)
{
cerr << "cant sell more shares than you posses"
<< "Transaction cancelled. ";
}
else
{
shares -= num;
share_val = price;
set_tot();
}
}
void Stock::update(double price)
{
share_val = price;
set_tot();
}
void Stock::show()
{
cout << "Company: " << company
<< " Shares: " << shares << " \n"
<< " share value: $" << share_val
<< " Total value: $ " << total_val << " \n";
}
int Stock::returnshares()
{
return shares;
}
const char * Stock::returncompany()
{
return company;
}
void Stock::compare(Stock stock2)
{
if (shares < stock2.returnshares())
{
cout << "Company" << stock2.returncompany() << "have higher share value than" << company;
}
else
{
cout << "Company" << company << "have higher share value than" << stock2.returncompany();
}
}
I get this error message.
In constructor ‘Stock::Stock(const char*, int, double)’:
Stock_class.cc:60:23: warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]
strcpy("company", co);
any idea how i can fix this issue ?
kind regards
Hampus hahne
It seems fairly obvious, you wrote
strcpy("company", co);
when you meant
strcpy(company, co);
Attention to detail is required.
Also
company[29]='\0';
is unnecessary because strcpy always adds a '\0' character, so you don't need to add one as well.
i think in your code strcpy(company,co) will fix you problem.
usage of strcpy was not proper please follow below link for more details:
https://www.geeksforgeeks.org/strcpy-in-c-cpp/
I was given an assignment to implement a quicksort algorithm into my C++ program. The homework is a part of series which started with objects and inheritance, but our lector didn't really explain quicksort to us.
However, I can't really understand how do I select the vector of an object that is to be sorted and how do I set the low and high limits.
Here is the code
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
#include <functional>
using namespace std;
template <typename T> T AskFor(string text) {
cout << text << endl;
T result;
cin >> result;
cin.clear();
return result;
}
class Vehicle {
public:
Vehicle(string producer, string model, int year)
: model(model) {
setProducer(producer);
setYear(year);
}
void output() {
cout << " producer(vehicle): " << producer << endl;
cout << " model(vehicle): " << model << endl;
cout << " year(vehicle): " << year << endl;
}
void setProducer(const string producer) {
if (isProducerValid(producer)) {
this->producer = producer;
}
}
string getProducer() const {
return producer;
}
void setModel(const string model) {
this->model = model;
}
string getModel() const {
return model;
}
void setYear(const int year) {
if (isYearValid(year)) {
this->year = year;
}
}
int getYear() const {
return year;
}
static bool isYearValid(int year) {
return year >= 1950 && year <= 2016;
}
static bool isProducerValid(string producer) {
static string PRODUCERS[] { "Toyota", "Audi", "BMW", "Mercedes" };
return find(begin(PRODUCERS), end(PRODUCERS), producer) != end(PRODUCERS);
}
private:
string producer;
string model;
int year;
};
class Vendor {
public:
Vendor(string v_name, string address, string phone, vector<string> delivery)
: v_name(v_name),
address(address),
delivery(delivery) {
setPhone(phone);
}
void setVendorName(const string v_name) {
this->v_name = v_name;
}
string getVendorName() const {
return v_name;
}
void setAddress(const string address) {
this->address = address;
}
string getAddress() const {
return address;
}
void setPhone(const string phone) {
this->phone = phone;
}
string getPhone() const {
return phone;
}
void setDelivery(const vector<string> delivery) {
this->delivery = delivery;
}
vector<string> getDelivery() const {
return delivery;
}
static bool isPhoneNumber(string phone) {
if (phone.empty()) {
return false;
}
return all_of(begin(phone), end(phone), isdigit);
}
private:
string v_name;
string address;
string phone;
vector<string> delivery;
};
class SparePart {
public:
SparePart(string id, string name, Vehicle* v, int price, int time_to_replace,
bool is_new = true, string description = "", string manual = "")
: id(id),
name(name),
vehicle(v),
price(price),
time_to_replace(time_to_replace),
is_new(is_new),
description(description),
manual(manual) {}
double replacementPrice() {
return price + time_to_replace * 20;
}
int warranty() const {
return is_new ? 36 : 3;
}
virtual void output() {
cout << " ID: " << id << endl;
cout << " name: " << name << endl;
vehicle->output();
if (is_new) cout << " new" << endl;
else {
cout << " recycled" << endl;
}
cout << " description: " << description << endl;
cout << " manual: " << manual << endl;
}
virtual ~SparePart() = 0;
void setId(const string id) {
this->id = id;
}
string getId() const {
return id;
}
void setName(const string name) {
this->name = name;
}
string getName() const {
return name;
}
void setDescription(const string description) {
this->description = description;
}
string getDescription() const {
return description;
}
void setManual(const string manual) {
this->manual = manual;
}
string getManual() const {
return manual;
}
void setPrice(const double price) {
this->price = price;
}
double getPrice() const {
return price;
}
void setIsNew(const bool is_new) {
this->is_new = is_new;
}
void setTimeToReplace(const int time_to_replace) {
this->time_to_replace = time_to_replace;
}
int getTimeToReplace() const {
return time_to_replace;
}
private:
string id;
string name;
string description;
string manual;
double price;
bool is_new;
int time_to_replace;
Vehicle* vehicle;
};
class AvailableSparePart : public SparePart {
public:
AvailableSparePart(string id, string name, Vehicle* v, int price, int time_to_replace,
int quantity, string location, bool is_new = true, string description = "", string manual = "")
: SparePart(id, name, v, price, time_to_replace, is_new, description, manual),
quantity(quantity),
location(location) {}
double price() {
return replacementPrice();
}
int time() {
return getTimeToReplace();
}
void output() {
cout << "Available Spare Part" << endl;
SparePart::output();
cout << " time: " << time() << endl;
cout << " price: " << price() << endl;
}
void setQuantity(const int quantity) {
this->quantity = quantity;
}
int getQuantity() const {
return quantity;
}
void setLocation(const string location) {
this->location = location;
}
string getLocation() const {
return location;
}
private:
int quantity;
string location;
};
class ContractedSparePart : public SparePart {
public:
ContractedSparePart(string id, string name, Vehicle* v, int price, int time_to_replace,
int delivery_time, double delivery_price, Vendor* vendor, bool is_new = true,
string description = "", string manual = "")
: SparePart(id, name, v, price, time_to_replace, is_new, description, manual),
delivery_time(delivery_time),
delivery_price(delivery_price),
vendor(vendor) {}
double price() {
return replacementPrice();
}
int time() {
return getTimeToReplace() + delivery_time;
}
void output() {
cout << "Contracted Spare Part" << endl;
SparePart::output();
cout << " time: " << time() << endl;
cout << " price: " << price() << endl;
}
void setDeliveryTime(const int delivery_time) {
this->delivery_time = delivery_time;
}
int getDeliveryTime() const {
return delivery_time;
}
void setDeliveryPrive(const double delivery_price) {
this->delivery_price = delivery_price;
}
double getDeliveryPrice() const {
return delivery_price;
}
private:
Vendor* vendor;
int delivery_time;
double delivery_price;
};
enum class Action {
ADD_VEHICLE,
ADD_VENDOR,
ADD_PART,
ADD_PART_QUANTITY,
LIST_PARTS,
CALCULATE_COST,
EXIT
};
Action menu() {
string prompt = "Choose an option:\n"
"1. Add a new vehicle\n"
"2. Add a new vendor\n"
"3. Add a new spare part\n"
"4. Add part quantity\n"
"5. List spare parts\n"
"6. Calculate the cost of replacement\n"
"7. Exit";
while (true) {
switch (AskFor<int>(prompt)) {
case 1:
return Action::ADD_VEHICLE; break;
case 2:
return Action::ADD_VENDOR; break;
case 3:
return Action::ADD_PART; break;
case 4:
return Action::ADD_PART_QUANTITY; break;
case 5:
return Action::LIST_PARTS; break;
case 6:
return Action::CALCULATE_COST; break;
case 7:
return Action::EXIT; break;
default:
cout << "Please enter a number between 1 and 6" << endl;
}
}
}
struct PartAndNumber {
PartAndNumber(SparePart* part, int number)
: part(part), number(number) {}
SparePart* part;
int number;
};
void add_vehicle(vector<Vehicle*>& vehicles);
void add_vendor(vector < Vendor*>& vendors);
void add_part(vector<PartAndNumber*>& parts, const vector<Vehicle*>& vehicles, const vector<Vendor*>& vendors);
void add_available_part(vector<PartAndNumber*>& parts, Vehicle* vehicle);
void add_contracted_part(vector<PartAndNumber*>& parts, Vehicle* vehicle, const vector<Vendor*>& vendors);
void add_part_number(vector<PartAndNumber*>& parts);
void list_parts(const vector<PartAndNumber*>& parts);
void calculate_cost(const vector<PartAndNumber*>& parts);
int main() {
vector<Vehicle*> vehicles;
vector<PartAndNumber*> parts;
vector<Vendor*> vendors;
while (true) {
Action action = menu();
switch (action) {
case Action::ADD_VEHICLE:
add_vehicle(vehicles);
break;
case Action::ADD_VENDOR:
add_vendor(vendors);
break;
case Action::ADD_PART:
add_part(parts,vehicles,vendors);
break;
case Action::ADD_PART_QUANTITY:
add_part_number(parts);
break;
case Action::LIST_PARTS:
list_parts(parts);
break;
case Action::CALCULATE_COST:
calculate_cost(parts);
break;
case Action::EXIT:
return 0;
}
}
}
void add_vehicle(vector<Vehicle*>& vehicles) {
string producer;
while (true) {
producer = AskFor<string>("New vehicle (producer): ");
if (Vehicle::isProducerValid(producer)) {
break;
}
cout << "Producer name is invalid. Try again." << endl;
}
string model = AskFor<string>("New vehicle (model):");
int year;
while (true) {
year = AskFor<int>("New vehicle (year):");
if (Vehicle::isYearValid(year)) {
break;
}
cout << "Year is invalid. Try again." << endl;
}
vehicles.push_back(new Vehicle(producer, model, year));
cout << "**************************************" << endl;
cout << "The vehicle was added to the database" << endl;
cout << "**************************************" << endl;
}
void add_vendor(vector <Vendor*>& vendors) {
string v_name = AskFor<string>("New vendor (name): ");
string address = AskFor<string>("New vendor (address): ");
string phone;
while (true) {
phone = AskFor<string>("New vendor (phone):");
if (Vendor::isPhoneNumber(phone)) {
break;
}
else cout << "Phone is invalid. Try again." << endl;
}
vector<string> delivery;
string del;
do {
cout << "New vendor(delivery) or q to stop: ";
if (del != "") {
delivery.push_back(del);
}
} while ((cin >> del) && del != "q");
vendors.push_back(new Vendor(v_name, address, phone, delivery));
cout << "**************************************" << endl;
cout << "The vendor was added to the database" << endl;
cout << "**************************************" << endl;
}
void add_part(vector<PartAndNumber*>& parts, const vector<Vehicle*>& vehicles, const vector<Vendor*>& vendors) {
string prompt = "Choose the type of spare part : Available(1) or Contracted(2); or q to exit : ";
do {
string model = AskFor<string>("Vehicle model: ");
Vehicle* vehicle = nullptr;
for (auto v : vehicles) {
if (v->getModel() == model) {
vehicle = v;
break;
}
}
if (vehicle == nullptr) {
cout << "Could not find a vehicle with this model." << endl;
return;
}
switch (AskFor<char>(prompt)) {
case '1':
add_available_part(parts, vehicle);
return;
break;
case '2':
add_contracted_part(parts, vehicle, vendors);
return;
break;
case 'q':
return;
break;
default:
cout << "No such option!";
}
} while (true);
}
void add_available_part(vector<PartAndNumber*>& parts, Vehicle* vehicle) {
string id = AskFor<string>("New spare part(id): ");
for (auto p : parts) {
if (p->part->getId() == id) {
cout << "Already available" << endl;
return;
}
}
string name = AskFor<string>("New spare part(name): ");
int price = AskFor<int>("New spare part(price): ");
int time_to_replace = AskFor<int>("New spare part(time to replace): ");
bool is_new = AskFor<bool>("New spare part(1 for new, 0 for recycled): ");
string description = AskFor<string>("New spare part(description): ");
string manual = AskFor<string>("New spare part(manual): ");
int quantity = AskFor<int>("New spare part(quantity): ");
string location = AskFor<string>("New spare part(location): ");
auto part = new AvailableSparePart(id, name, vehicle, price, time_to_replace, quantity, location, is_new, description, manual);
parts.push_back(new PartAndNumber(part, 0));
cout << "**************************************" << endl;
cout << "The spare part was added to the database" << endl;
cout << "**************************************" << endl;
}
void add_contracted_part(vector<PartAndNumber*>& parts, Vehicle* vehicle, const vector<Vendor*>& vendors) {
string id = AskFor<string>("New spare part(id): ");
for (auto p : parts) {
if (p->part->getId() == id) {
cout << "Already available" << endl;
return;
}
}
string v_name = AskFor<string>("New spare part(vendor name): ");
Vendor* vendor = nullptr;
for (auto v : vendors) {
if (v->getVendorName() == v_name) {
vendor = v;
break;
}
}
if (vendor == nullptr) {
cout << "Could not find a vendor with this name." << endl;
return;
}
string name = AskFor<string>("New spare part(name): ");
int price = AskFor<int>("New spare part(price): ");
int time_to_replace = AskFor<int>("New spare part(time to replace): ");
bool is_new = AskFor<bool>("New spare part(1 for new, 0 for recycled): ");
string description = AskFor<string>("New spare part(description): ");
string manual = AskFor<string>("New spare part(manual): ");
int delivery_time = AskFor<int>("New spare part(delivery time): ");
double delivery_price = AskFor<double>("New spare part(delivery price): ");
auto part = new ContractedSparePart(id, name, vehicle, price, time_to_replace, delivery_time, delivery_price, vendor, is_new, description, manual);
parts.push_back(new PartAndNumber(part, 0));
cout << "**************************************" << endl;
cout << "The spare part was added to the database" << endl;
cout << "**************************************" << endl;
}
void add_part_number(vector<PartAndNumber*>& parts) {
string id = AskFor<string>("Spare part (id): ");
for (auto p : parts) {
if (p->part->getId() == id) {
int parts_number = AskFor<int>("Number of parts: ");
p->number = parts_number;
cout << "***************************************************" << endl;
cout << "The number of spare parts was added to the database" << endl;
cout << "***************************************************" << endl;
return;
}
}
cout << "A spare part with this ID is not available.";
}
void list_parts(const vector<PartAndNumber*>& parts) {
double total_price = 0;
for (auto p : parts) {
p->part->output();
cout << endl;
double total_current_price = p->part->replacementPrice() * p->part->getTimeToReplace();
total_price = +total_current_price;
}
quicksort(parts, , parts.back);
cout << "The total price is" << total_price << endl;
}
void calculate_cost(const vector<PartAndNumber*>& parts) {
string id = AskFor<string>("Spare part(id): ");
for (auto p : parts) {
if (p->part->getId() == id) {
cout << "The cost for replacement is $" << p->part->replacementPrice() << endl;
return;
}
}
cout << "A spare part with this ID is not available.";
}
SparePart::~SparePart() {}
template <class Comparable>
void quicksort(vector<Comparable>& a)
{
quicksort(a, 0, a.size() - 1);
}
template <class Comparable>
void quicksort(vector<Comparable>& a, double low, double high)
{
if (low + 10 > high) {
insertionSort(a);
}
else {
double middle = (low + high) / 2;
if (a[middle] < a[low]) swap(a[low], a[middle]);
if (a[high] < a[low]) swap(a[low], a[high]);
if (a[high] < a[middle]) swap(a[middle], a[high]);
Comparable pivot = a[middle];
swap(a[middle], a[high - 1]);
int i, j;
for (i = low, j = high - 1; ;) {
while (a[++i] < pivot) {}
while (pivot < a[--j]) {}
if (i < j) swap(a[i], a[j]);
else break;
}
swap(a[i], a[high - 1]);
quicksort(a, low, i - 1);
quicksort(a, i + 1, high);
}
}
Thank you for the help!
Elements of Your vector are pointers! The easiest way is to add to class PartAndNumber
operator<(const PartAndNumber *other)
{
return this->part->id - other->part->id;
}
So I was able to fix it, however, the operator doesn't seem to be comparing them both since I always get false. There seems to be an error with the pLoan where it is not comparing both of them.
My code is
#include <string>
#include <iostream>
#include <sstream>
using namespace std;
//Vehicle Class
class Vehicle {
public:
Vehicle();
void setPrice(double a);
void setMpg(int a);
double getPrice() const;
int getMpg() const;
void printVehicle() const;
Vehicle(double price, int mpg);
private:
double price;
int mpg;
};
//Loan Class
class Loan {
public:
void setBank(string a);
void setLoan(double a);
string getBank() const;
double getLoan() const;
void printLoan() const;
Loan(string bank = "", double loan = 0);
private:
string bank;
double loan;
};
//Car Class
class Car : public Vehicle {
public:
Car(double price = 0, int mpg = 0, string bank = "", double loan = 0, string name = "", int element = 0);
void setName(string a);
void setLoan(string b, double l, int element);
string getName() const;
void printFull() const;
void setNbrOfLoans(int a);
int getNbrOfLoans() const;
Loan* getpLoan() const;
~Car();
private:
string name;
Loan* pLoan;
int nbrOfLoans;
};
bool operator==(const Car &car1, const Car &car2) {
Loan* pLoan1 = car1.getpLoan();
Loan* pLoan2 = car2.getpLoan();
return ((car1.getPrice() == car2.getPrice()) && (car1.getMpg() == car2.getMpg()) && (car1.getName() == car2.getName())
&& (car1.getNbrOfLoans() == car2.getNbrOfLoans()) &&
(pLoan1[0].getBank() == pLoan2[0].getBank()) && (pLoan1[0].getLoan() == pLoan2[0].getLoan()));
}
//Main
int main() {
Car car1(24800, 22, "Citi", 21600, "Mustang", 1);
Car* pCar1 = &car1;
pCar1->setLoan("Citi", 21600, 0);
pCar1->printFull();
pCar1->setNbrOfLoans(1);
Car car2;
Car* pCar2 = &car2;
cout << boolalpha;
cout << "Enter the price of the car: ";
double price;
cin >> price;
pCar2->setPrice(price);
cout << "Enter the mpg: ";
int mpg;
cin >> mpg;
pCar2->setMpg(mpg);
cout << "Enter the name of the car: ";
string name;
cin >> name;
pCar2->setName(name);
string bank;
double loan;
int index;
cout << "Enter the amount of loans you obtained: ";
cin >> index;
pCar2->setNbrOfLoans(index);
for (int i = 0; i < index; i++)
{
cout << "Enter the name of bank " << i + 1 << ": ";
cin >> bank;
cout << "Enter the amount of loan " << i + 1 << ": ";
cin >> loan;
pCar2->setLoan(bank, loan, i);
}
if (pCar1 == pCar2)
cout << "Cars are the same. ";
else
cout << "Cars are not the same. ";
cout << endl;
pCar2->printFull();
return 0;
}
////////////////////////////////////////////////////////////////////////////////////////
//Vehicle class function definitions
////////////////////////////////////////////////////////////////////////////////////////
Vehicle::Vehicle() {
price = 0;
mpg = 0;
}
Vehicle::Vehicle(double price, int mpg) {
price = price;
mpg = mpg;
}
void Vehicle::setPrice(double a) {
price = a;
}
void Vehicle::setMpg(int a) {
mpg = a;
}
double Vehicle::getPrice() const {
return price;
}
int Vehicle::getMpg() const {
return mpg;
}
void Vehicle::printVehicle() const {
cout << "Price: " << price << endl;
cout << "MPG: " << mpg << endl;
}
////////////////////////////////////////////////////////////////////////////////////////
//Loan Class function definitions
///////////////////////////////////////////////////////////////////////////////////////
Loan::Loan(string bank, double loan) {
Loan::bank = bank;
Loan::loan = loan;
}
void Loan::setBank(string a) {
bank = a;
}
void Loan::setLoan(double a) {
loan = a;
}
string Loan::getBank() const {
return bank;
}
double Loan::getLoan() const {
return loan;
}
void Loan::printLoan() const {
cout << "Bank: " << bank << endl;
cout << "Loan: " << loan << endl;
}
////////////////////////////////////////////////////////////////////////////////////
//Car Class function definitions
////////////////////////////////////////////////////////////////////////////////////
Car::Car(double price, int mpg, string bank, double loan, string name, int element) : Vehicle(price, mpg)
{
nbrOfLoans = element;
Car::name = name;
setMpg(mpg);
setPrice(price);
pLoan = new Loan[nbrOfLoans];
}
Loan* Car::getpLoan() const{
return pLoan;
}
void Car::setName(string a) {
name = a;
}
void Car::setLoan(string b, double l, int element) {
pLoan[element].setBank(b);
pLoan[element].setLoan(l);
}
string Car::getName() const {
return name;
}
int Car::getNbrOfLoans() const {
return nbrOfLoans;
}
void Car::setNbrOfLoans(int a) {
nbrOfLoans = a;
if (pLoan != NULL)
delete[] pLoan;
pLoan = new Loan[nbrOfLoans];
}
void Car::printFull() const {
cout << endl << "Car name: " << name << endl;
cout << "Price: " << getPrice() << endl;
cout << "MPG: " << getMpg() << endl;
for (int i = 0; i < nbrOfLoans; i++)
{
cout << "Loan #" << i + 1 << "." << endl;
cout << "Bank: " << pLoan[i].getBank();
cout << endl;
cout << "Loan amount: " << pLoan[i].getLoan();
cout << endl;
}
}
Car::~Car() {
delete[] pLoan;
}
Output:
IS always cars are not the same even when they are
Your main code is not calling your operator ==:
if (pCar1 == pCar2)
cout << "Cars are the same. ";
else
cout << "Cars are not the same. ";
here you're comparing the two pointers. To compare the two pointed-to objects you need
if (*pCar1 == *pCar2) ...
One more error:
pCar1->setLoan("Citi", 21600, 0);
pCar1->printFull();
pCar1->setNbrOfLoans(1);
setNbrOfLoans must be located before setLoan:
pCar1->setNbrOfLoans(1);
pCar1->setLoan("Citi", 21600, 0);
pCar1->printFull();
My code is supposed to read 16 lines from a text file, and passing them into an array of 4 Objects, each with 4 attributes. The problem im encountering is that while everything seems to work fine on passing the text details to the array, the 1st array element of the last object in the array is not the one supposed to be! I am really stuck!
My code is :
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int CDsize;
class CD {
public:
// constructors
CD();
CD(string arist, string title, int year, double price);
// getter methods
string getArtist() const { return this->artist; }
string getTitle() const { return this->title; }
int getYear() const { return this->year; }
double getPrice() const { return this->price; }
// setter methods - inline functions
void setArtist(const string artist) { this->artist = artist; }
void setTitle(const string title) { this->title = title; }
void setYear(const int year) { this->year = year; }
void setPrice(const double price) { this->price = price; }
// option methods
private:
string artist;
string title;
int year;
double price;
};
/*Text menu option 1/*
void printallcds(CD MAX_CDS[])
{
int d;
for (d=0; d<=CDsize; d++)
{
cout << "CD Number : " << d << "/ Artist : " << MAX_CDS[d].getArtist() << "/
Title : " << cout << MAX_CDS[d].getTitle() << "/ Year of Release : " <<
MAX_CDS[d].getYear() << "/ Price : " <<
cout << MAX_CDS[d].getPrice() << endl;
}
}*/
int main() {
CD MAX_CDS[3];
int CDsize = (sizeof(MAX_CDS) / sizeof(MAX_CDS[0]));
ifstream CDfile("mystock.txt");
string data;
int yeardata;
double pricedata;
int i;
for (i = 0; i < 4; i++) {
getline(CDfile, data);
MAX_CDS[i].setArtist(data);
getline(CDfile, data);
MAX_CDS[i].setTitle(data);
getline(CDfile, data);
stringstream yearstream(data);
yearstream >> yeardata;
MAX_CDS[i].setYear(yeardata);
getline(CDfile, data);
stringstream pricestream(data);
pricestream >> pricedata;
MAX_CDS[i].setPrice(pricedata);
}
CDfile.close();
// testing
cout << MAX_CDS[3].getArtist() << endl; // error !!!
cout << MAX_CDS[3].getTitle() << endl;
cout << MAX_CDS[3].getYear() << endl;
cout << MAX_CDS[3].getPrice() << endl;
return 0;
}
// constructors implementation
CD::CD() {}
CD::CD(string artist, string title, int year, double price) {
this->artist = artist;
this->title = title;
this->year = year;
this->price = price;
}
}
You only have space for 3 items in MAX_CDS (see CD MAX_CDS[3];), yet you're referencing the 4th item in your error.
MAX_CDS[3] // Actually represents the 4th item
Counting starts from 0 in C++.
So, to reference the 3rd item, in your case the last item, use MAX_CDS[2] or MAX_CDS[CDSize-1].
cout << MAX_CDS[CDSize-1].getArtist() << endl;
cout << MAX_CDS[CDSize-1].getTitle() << endl;
cout << MAX_CDS[CDSize-1].getYear() << endl;
cout << MAX_CDS[CDSize-1].getPrice() << endl;
Rereading your question, you probably want more items!
CD MAX_CDS[4]; // Now you have 4 items available: indexed 0, 1, 2, and 3