hello all i am working on a school prject called inventory inquisitor. the specifications are as follows:
enter image description here
so far i have created a class in which contains a struct and a vector of this struct.
all im trying to do so far is get the class to display the struct just to know it works but when i compile it and run it nothing happens. here is the code. excuse whatever rookie mistakes i have made i am very new with classes, and vectors. thanks you in advance!
//Inventory Inquisitor.cpp
#include <iostream>
#include <string>
#include <cctype> //for toupper
#include <fstream>
#include <vector>
using namespace std;
class Inventory
{
private:
struct item
{
string Description = " ";
double Quantity = 0;
double Wholesalescost = 0;
double Retailcost = 0;
string Dateadded = " ";
};
vector<item> Inv;
public:
void Display();
};
void Inventory::Display()
{
Inv[0].Description = "english";
Inv[0].Quantity = 1;
Inv[0].Wholesalescost = 100;
Inv[0].Retailcost = 200;
Inv[0].Dateadded = "3/8/2018";
cout << Inv[0].Description << endl;
cout << Inv[0].Quantity << endl;
cout << Inv[0].Wholesalescost << endl;
cout << Inv[0].Retailcost << endl;
cout << Inv[0].Dateadded << endl;
}
int main()
{
Inventory inst1;
inst1.Display();
}
You have to put something into the vector before accessing it:
// Create an item
item i;
i.Description = "english";
i.Quantity = 1;
i.Wholesalescost = 100;
i.Retailcost = 200;
i.Dateadded = 3/8/2018;
// The vector is empty, size() == 0
// Add it to the vector
Inv.push_back(i);
// Now the vector has 1 item, size() == 1
// Now you can print it
cout << Inv.at(0).Description << endl;
cout << Inv.at(0).Quantity << endl;
cout << Inv.at(0).Wholesalescost << endl;
cout << Inv.at(0).Retailcost << endl;
cout << Inv.at(0).Dateadded << endl;
According to your assignment, you will most likely change to function to print an existing item. You will have another function to add items to the vector.
void Inventory::Display(int index)
{
// Print an item already in the vector
if (index >= 0 && index < Inv.size()) {
cout << Inv.at(index).Description << endl;
cout << Inv.at(index).Quantity << endl;
cout << Inv.at(index).Wholesalescost << endl;
cout << Inv.at(index).Retailcost << endl;
cout << Inv.at(index).Dateadded << endl;
}
}
Related
Its a card game, I draw 2 cards from the deck (the array) with the help of two functions.
Each element of the array represent one card with a symbol Spades, Hearts, Diamonds or Clubs.
These numbers in the array \5 \4 \3 \6, represent Clubs, Dimaond, Heatrs, spades (just if ur curious)
The problem!
When I draw a card two times I sometimes get Duplicates.. The same card twice.
How do I make sure the same card cant be drawn twice?
How do I avoid getting duplicates??
This is how the code Looks like.
Some INFO about the array...
The further in, in the array, the higher value the element has.
I have shortened the array... for easy testing of a solution... later the array will be 52 elements.
array<string, 3> cards = { "Ess \5", "Ess \4", "Ess \3" };
//The function.
pair<string, int> draw_card()
{
int random_index = rand() % 52;
string card = cards[random_index];
return { card, random_index };
}
int main()
{
// Seed, random.
srand((unsigned int)time(NULL));
// Calling the function 2 times.
pair<string, int> you_drew = draw_card();
cout << "You drew: " << you_drew.first << endl;
pair<string, int> comp_drew = draw_card();
cout << "Computer drew: " << comp_drew.first << endl;
// Deciding the winner.
int your_score{ 0 };
int the_computers_score{ 0 };
if (you_drew.second > comp_drew.second) {
cout << "You Won!" << endl;
your_score++;
}
else if (you_drew.second < comp_drew.second) {
cout << "You Lost!" << endl;
the_computers_score++;
}
return 0;
}
Everything is working fine, EXCEPT sometimes I get duplicates... I want to make sure I can Not get that...
Somehow when I draw a card the element in the array should not be able to be drawn.. I want to avoid getting duplicates. Please help me!
Shouldnt something like this work? its not but.. shouldnt it?
pair<string, int> comp_drew = draw_card();
if (you_drew == comp_drew) {
bool run8 = true;
while (run8) {
pair<string, int> comp_drew = draw_card();
if (comp_drew != you_drew) {
cout << "Computer drew: " << comp_drew.first << endl;
run8 = false;
}
}
}
Or maybe another solution..
Perhaps after calling the function one time i can delete the return index from the array?
You can swap the drawn card to the end and only choose an index smaller than 51 the next time.
int array_len = 52; // global variables are not great, but it's easier here
pair<string, int> draw_card()
{
int random_index = rand() % array_len;
--array_len;
string card = cards[random_index];
std::swap(cards[random_index], cards[array_len]);
return { card, random_index };
}
There are many different ways to do this.
std::random_shuffle
#include <iostream>
#include <algorithm>
using namespace std;
class CardMachine {
static unsigned constexpr DECK_SIZE = 4;
int cards[DECK_SIZE] = {1,2,3,4};
int lastUsedCardIndex = -1;
public:
int getCard() {
if (lastUsedCardIndex == DECK_SIZE - 1)
shuffle();
return cards[++lastUsedCardIndex];
}
void shuffle() {
random_shuffle(begin(cards), end(cards));
}
};
int main()
{
CardMachine cardMachine = CardMachine();
cout << "unhsuffled - 1,2,3,4 without duplicates:" << endl;
cout << cardMachine.getCard() << endl;
cout << cardMachine.getCard() << endl;
cout << cardMachine.getCard() << endl;
cout << cardMachine.getCard() << endl;
cout << "Shuffled. Random order, and still no duplicates:" << endl;
cardMachine.shuffle(); // or call getCard which can shuffle
cout << cardMachine.getCard() << endl;
cout << cardMachine.getCard() << endl;
cout << cardMachine.getCard() << endl;
cout << cardMachine.getCard() << endl;
return EXIT_SUCCESS;
}
Mark Card as Taken
#include <iostream>
#include <random>
using namespace std;
class CardMachine {
static unsigned constexpr DECK_SIZE = 4;
inline static int constexpr cards[DECK_SIZE] = {1,2,3,4};
bool cardIsGone[DECK_SIZE] = {false, false, false, false};
public:
int getCard() {
while(true) {
int const RANDOM_INDEX = rand()%DECK_SIZE;
if(!cardIsGone[RANDOM_INDEX]) {
cardIsGone[RANDOM_INDEX] = true;
return cards[RANDOM_INDEX];
}
}
}
void shuffle() {
for(bool &isGone : cardIsGone)
isGone = false;
lastUsedCardIndex = -1;
}
};
int main()
{
CardMachine cardMachine = CardMachine();
cout << "Shuffled - Random order, and still no duplicates:" << endl;
cout << cardMachine.getCard() << endl;
cout << cardMachine.getCard() << endl;
cout << cardMachine.getCard() << endl;
cout << cardMachine.getCard() << endl;
cout << "Shuffled. Random order, and still no duplicates:" << endl;
cardMachine.shuffle(); // Causes infinite loop if you call getCard DECK_SIZE + 1 times
cout << cardMachine.getCard() << endl;
cout << cardMachine.getCard() << endl;
cout << cardMachine.getCard() << endl;
cout << cardMachine.getCard() << endl;
return EXIT_SUCCESS;
}
It's not the most efficient solution, but with small values like 52, it should be instant.
Swap Used Cards to Back and Keep Track of Range
#include <iostream>
#include <random>
using namespace std;
class CardMachine {
static unsigned constexpr DECK_SIZE = 4;
int cards[DECK_SIZE] = {1,2,3,4};
int lastCardIndexExlusive = DECK_SIZE;
public:
int getCard() {
int const RANDOM_INDEX = rand()%lastCardIndexExlusive;
swap(cards[RANDOM_INDEX],cards[lastCardIndexExlusive - 1]);
return cards[--lastCardIndexExlusive];
}
void shuffle() {
lastCardIndexExlusive = DECK_SIZE;
}
};
int main()
{
CardMachine cardMachine = CardMachine();
cout << "Shuffled - Random order, and still no duplicates:" << endl;
cout << cardMachine.getCard() << endl;
cout << cardMachine.getCard() << endl;
cout << cardMachine.getCard() << endl;
cout << cardMachine.getCard() << endl;
cout << "Shuffled. Random order, and still no duplicates:" << endl;
cardMachine.shuffle(); // Causes exception if getCard DECK_SIZE + 1 times
cout << cardMachine.getCard() << endl;
cout << cardMachine.getCard() << endl;
cout << cardMachine.getCard() << endl;
cout << cardMachine.getCard() << endl;
return EXIT_SUCCESS;
}
Remember Last Card
#include <iostream>
#include <random>
using namespace std;
class CardMachine {
static unsigned constexpr DECK_SIZE = 4;
int cards[DECK_SIZE] = {1,2,3,4};
int lastCard = -1;
public:
int getCard() {
int const RANDOM_INDEX = rand()%DECK_SIZE;
if (lastCard == RANDOM_INDEX) {
return getCard();
}
lastCard = cards[RANDOM_INDEX];
return lastCard;
}
void shuffle() {
lastCard = -1;
}
};
int main()
{
CardMachine cardMachine = CardMachine();
cout << "Shuffled - Random order, and still no duplicates, but only able to produce 2:" << endl;
cout << cardMachine.getCard() << endl;
cout << cardMachine.getCard() << endl;
cout << "Shuffled. Random order, and still no duplicates:" << endl;
cardMachine.shuffle(); // Causes potential duplicates if getCards 3+ times
cout << cardMachine.getCard() << endl;
cout << cardMachine.getCard() << endl;
return EXIT_SUCCESS;
}
All of these solutions make use of a class to hold state for use in getCard to make sure we get the right behavior.
I am very very new to C++, and I am trying to create a math engine
I have a class called Point, and objects from this class need to be able to hold an unknown amount of dimension values. I have a variable called DAmount that is decided when a point is created. I want to have a method that takes DAmount, and creates that many variables connected to the Point object.
For example, I declare a Point named "SixDPoint" and then set its DAmount to 6. I then use a method named CreateDVars to create six variables connected to the object "SixDPoint". I can then use these six variables to act as XYZ+ axises.
I have no idea how to do this. Here is some code to explain what I am trying to do. Thanks so much
#include <iostream>
using namespace std;
class Point
{
public:
int DAmount;
void CreateDVars(int)
{
//Variable declaration Function
}
};
int main()
{
Point SixDPoint; //declaring a Point named SixDPoint
SixDPoint.DAmount = 6; // this sets the dimension amount, of SixDPoint, to 6
SixDPoint.D1 = 1;
SixDPoint.D2 = 1;
SixDPoint.D3 = 1;
SixDPoint.D4 = 1;
SixDPoint.D5 = 1;
SixDPoint.D6 = 1;
//this should assign all six dimensions of SixDPoint, to 1
cout << SixDPoint.D1 << "/n";
cout << SixDPoint.D2 << "/n";
cout << SixDPoint.D3 << "/n";
cout << SixDPoint.D4 << "/n";
cout << SixDPoint.D5 << "/n";
cout << SixDPoint.D6 << "/n";
//this should print out all of the coordinates of SixDPoint
return 0;
}
I believe you want something like this:
#include <iostream>
#include <vector>
using namespace std;
class Point
{
public:
int DAmount;
void CreateDVars(int k)
{
dim.resize(k);
}
int& operator[](int k)
{
if (k >= 0 && k < dim.size())
return dim[k];
}
private:
vector<int> dim;
};
int main()
{
Point SixDPoint; //declaring a Point named SixDPoint
SixDPoint.CreateDVars(6);
SixDPoint[0] = 1;
SixDPoint[1] = 1;
SixDPoint[2] = 1;
SixDPoint[3] = 1;
SixDPoint[4] = 1;
SixDPoint[5] = 1;
//this should assign all six dimensions of SixDPoint, to 1
cout << SixDPoint[0] << "/n";
cout << SixDPoint[1] << "/n";
cout << SixDPoint[2] << "/n";
cout << SixDPoint[3] << "/n";
cout << SixDPoint[4] << "/n";
cout << SixDPoint[5] << "/n";
//this should print out all of the coordinates of SixDPoint
return 0;
}
I have a class of light bulbs. There are methods and constructors in this class. There is even a destructor) The problem is that I have to determine and display information about class members with type "n" in the TEST() method (LED lamps).
To implement this task, he developed the gettype() method, which returns the type of an object, and, in fact, the TEST() method, which displays information about light bulbs.
The problem is that nothing works for me. I tried a lot of things, but it doesn’t work out for me to implement this task. I'm new to programming (
Code:
#include <iostream>
using namespace std;
class lamp
{
public:
// methods
void TEST(void);
char* gettype (void);
void INIT(void);
void SHOW(void);
// construcrors
lamp();
lamp(const char *t, int powe, const char *c, double cos);
lamp(const lamp & obj);
// destructor
~lamp();
private:
// data
char type[100]; // LED, energy-saving or incandescent lamp
int power; // LED lamp - "n"
char color[100];
double cost;
};
lamp::lamp() {
cout << "This object was created in the default constructor.\n";
strcpy(type, "");
power = 0;
strcpy(color, "");
cost = 0;
}
lamp::lamp(const char *t, int powe, const char *c, double cos) {
cout << "This object was created in the constructor with parameters.\n";
strcpy(type, t); //*t
power = powe;
strcpy(color, c); //*c
cost = cos;
}
lamp::lamp(const lamp & obj) {
cout << "This object was created in the copy constructor.\n";
strcpy(type, obj.type);
power = obj.power;
strcpy(color, obj.color);
cost = obj.cost;
}
lamp::~lamp() {
cout << "Deletion of object by destructor.\n";
}
void lamp::SHOW(void) {
cout << "Lamp Information:\n";
cout << "\nType > " << type;
cout << "\nPower > " << power;
cout << "\nColor > " << color;
cout << "\nCost > " << cost << endl;
}
void lamp::INIT(void) {
cout << "Enter lamp information:\n";
cout << "\nType (if LED, then n) > "; cin >> type;
cout << "\nPower > "; cin >> power;
cout << "\nColor > "; cin >> color;
cout << "\nCost > "; cin >> cost;
}
char* lamp::gettype (void) {
return type;
}
void lamp::TEST(void) {
cout << "\nType > " << type;
cout << "\nPower > " << power;
cout << "\nColor > " << color;
cout << "\nCost > " << cost << endl;
}
void main() {
setlocale(0, "");
// default constructor for 1 class instance
lamp l1;
cout << "Entering data for the first product." << endl;
l1.INIT();
// constructor with parameters for 2 class instances
cout << endl << "Information about the second object: \n";
lamp l2("n", 950, "yellow", 1580);
// copy constructor for the third object
cout << endl << "Information about the third object: \n";
lamp l3(l2);
// Derived information about all the lamps using the method SHOW
l1.SHOW();
l2.SHOW();
l3.SHOW();
// I create an array of two objects using the default constructor
lamp la[2];
I enter data into an array of objects using the method INIT
cout << "Fill an array of objects with 2 elements." << endl;
for(int i = 0; i < 2; i++) {
la[i].INIT();
}
// I output data from an array of objects using the method SHOW
cout << "Showing items." << endl;
for (int i = 0; i < 2; i++) {
la[i].SHOW();
}
// looking for and displaying information about LED lamps
cout << "Search and display information about LED lamps." << endl;
for (int i = 0; i < 3; i++) {
if (la[i].gettype() == "n") {
cout << endl << " lamp number : " << (i + 1) << endl;
la[i].TEST();
cout << endl;
}
}
system("pause");
}
There are several errors in your code:
strcpy is included in <cstring> which is missed. You need to add it in the beginning:
#include <cstring>
main() function should be declared as int main() and you need to add a return statement
int main() {
//YOUR CODE HERE
return 0;
}
You missed a comment sign at line 104
lamp la[2];
//I enter data into an array of objects using the method INIT
cout << "Fill an array of objects with 2 elements." << endl;
After fixed, your code should be able to run.
I am asked to do this code and i need to use array or something similar to print out different classes. The only way i know is individually doing every single class is there a faster way of doing this. Following is the way i am using at the moment.
Ground_Transport Gobj;
Air_Transport Aobj;
Sea_Transport Sobj;
Car Cobj;
Train Tobj;
Bus Bobj;
Gobj.estimate_time();
Gobj.estimate_cost();
cout << Gobj.getName() << endl;
Bobj.estimate_time();
Bobj.estimate_cost();
cout << Bobj.getName() << endl;
Sobj.estimate_time();
Sobj.estimate_cost();
cout<<Sobj.getName()<<endl;
Aobj.estimate_time();
Aobj.estimate_cost();
cout << Aobj.getName() << endl;
Cobj.estimate_time();
Cobj.estimate_cost();
cout << Cobj.getName() << endl;
Tobj.estimate_time();
Tobj.estimate_cost();
cout << Tobj.getName() << endl;
Transport_KL_Penang Kobj;
cout << Kobj.getName() << endl;
This is the header file Transport_KL_Penang
#include <iostream>
#include <string>
using namespace std;
class Transport_KL_Penang
{
public:
Transport_KL_Penang() {}
virtual string getName() {
return Name;
}
int Time_in_hours1 ;
int Time_in_hours2 ;
int Cost_in_RM1 ;
int Cost_in_RM2 ;
void estimate_time() ;
void estimate_cost() ;
private:
static string Name;
};
void Transport_KL_Penang::estimate_time()
{
cout << "It takes " << Time_in_hours1 << "-" << Time_in_hours2 <<
" hours if you use " << Name << endl;
}
void Transport_KL_Penang::estimate_cost()
{
cout << "It will cost around " << Cost_in_RM1 << "-" << Cost_in_RM2 <<
"RM if you use " << Name << endl;
}
If you don't need a specific object name, you can write something as a code below, creating a multiples generics objects:
#include <iostream>
#include <cstdlib>
#include <time.h>
class Myclass {
private:
int randTime;
float cost;
public:
void estimate_time(){
randTime = rand()%100;
}
void estimate_cost(){
cost = randTime * 0.2;
}
float getEstimateCost(){
return cost;
}
};
int main(){
srand(time(NULL));
int numberOfObjects = 7;
Myclass obj[numberOfObjects];
//input
for(int i = 0; i < numberOfObjects; i++){
obj[i].estimate_time();
obj[i].estimate_cost();
}
// printing
for(int i = 0; i < numberOfObjects; i++){
std::cout << obj[i].getEstimateCost() << std::endl;
}
return 0;
}
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
void armySkirmish();
void battleOutcome();
string commander = "";
int numberOfHumans = 0;
int numberOfZombies = 0;
class ArmyValues
{
protected:
double attackPower;
double defensePower;
double healthPoints;
public:
void setAttackPower(double a)
{
attackPower = a;
}
void setDefensePower(double d)
{
defensePower = d;
}
void setHealthPoints(double h)
{
healthPoints = h * (defensePower * .1);
}
};
class Zombies: public ArmyValues
{
};
class Humans: public ArmyValues
{
};
int main(int argc, char ** argv)
{
cout << "Input Commander's Name: " << endl;
cin >> commander;
cout << "Enter Number of Human Warriors: " << endl;
cin >> numberOfHumans;
cout << "Enter Number of Zombie Warriors: " << endl;
cin >> numberOfZombies;
armySkirmish();
battleOutcome();
return 0;
}
void armySkirmish()
{
cout << "\nThe Humans tense as the sound of the undead shuffle towards them." << endl;
cout << commander << " shuffles forward with a determined look." << endl;
cout << "The undead form up into ranks and growl a war chant!" << endl;
cout << commander <<" shouts, CHARGE!!!" << endl;
cout << endl;
cout << "Warriors from both sides blitz across the field!" << endl;
cout << endl;
cout << "*The Carnage has begun!*" << endl;
cout << "*Steal, Sparks, and Flesh flies" << endl;
}
void battleOutcome()
{
int zombieLives = numberOfZombies;
int humanLives = numberOfHumans;
int randomNumber = 0;
int humanDeath = 0;
int zombieDeath = 0;
double newHumanLife = 0;
double newZombieLife = 0;
Zombies zombieBattleData;
Humans humanBattleData;
srand(time(NULL));
zombieBattleData.setAttackPower(20.0);
humanBattleData.setAttackPower(35.0);
zombieBattleData.setDefensePower(15.0);
humanBattleData.setDefensePower(20.0);
zombieBattleData.setHealthPoints(150.0);
humanBattleData.setHealthPoints(300.0);
while(zombieLives && humanLives > 0)
{
randomNumber = 1+(rand()%10);
if(randomNumber < 6)
{
newHumanLife = humanBattleData.healthPoints - zombieBattleData.attackPower;
if(newHumanLife <= 0)
{
humanLives--;
humanDeath++;
}
}else
{
newZombieLife = zombieBattleData.healthPoints - humanBattleData.attackPower;
if(newZombieLife <= 0)
{
zombieLives--;
zombieDeath++;
}
}
}
if(zombieLives <= 0)
{
cout << "Humans have emerged victorious!" << endl;
cout << "Human Deaths: " << humanDeath << "Zombie Deaths: " << zombieDeath << endl;
}else if(humanLives <= 0)
{
cout << "Zombies have emerges victorious!" << endl;
cout << "Human Deaths: " << humanDeath << "Zombie Deaths: " << zombieDeath << endl;
}
I know the code wont run properly as of now. What I was doing was a test run to make sure I was receiving no errors. The two errors I'm getting are:
armySimulatorMain.cpp:25:10: error: 'double ArmyValues::healthPoints' is protected
armySimulatorMain.cpp:115:67: error: within this context.
newHumanLife = humanBattleData.healthPoints - zombieBattleData.attackPower;
This is the case for Attack Power and Health Power however, Defense power is clearing the errors. i don't understand why they are getting flagged. I'm changing the variable through the public function so shouldn't this be allowed?
Also, I'm calling three variables outside of all functions because they are being used by multiple functions. How can I plug those variables somewhere I don't like that they are floating freely above everything?
Thanks guys I can't believe I forgot about getters... Anyway the code runs now much appreciated I'll make sure to remember this time xD
It's not complaining about the line where you set the values; as you say, that uses a public function. But here, you try to read the protected member variables:
newHumanLife = humanBattleData.healthPoints - zombieBattleData.attackPower;
You only try to read two variables, and those are the ones it complains about.
You'll need a public getter function to read the values.
You need to do something like:
public:
double gethealthPoints()
{
return healthPoints;
}
because attackPower, defensePower, healthPoints are all protected, so if you want to access to any of them you need a getter, otherwise you will always receive an protect error