When I use the object function set_and_make_variable I send it a name and value which both work correctly. However then when I go to use show current_variables it acts like I never set the values for both integers, and integers_names. I thought you could modify the variables arrays from the functions associated with the class without references or pointers.
Am I not correct?
void reset_name(string *variable_names)
{
for (int i = 0; i < 100; i++)
{
variable_names[i] = "";
}
}
void reset_int_value(int *variable_value)
{
for (int i = 0; i < 100; i++)
{
variable_value[i] = 0;
}
}
int find_next(string variable_names[100])
{
for (int i = 0; i < 100; i++)
{
if (variable_names[i] == "")
{
return i;
}
}
}
//*****************************************************************
class variables_integers
{
public:
string integer_names[100];
int integers[100];
variables_integers(void);
void set_and_make_variable(string, int);
void show_current_variables(void);
};
variables_integers::variables_integers(void)
{
reset_int_value(integers);
reset_name(integer_names);
}
void variables_integers::show_current_variables(void)
{
cout << "INTEGERS:" << endl;
for (int i = 0; i < (find_next(integer_names)); i++)
{
cout << integer_names[i] << " = " << integers[i] << endl;
}
}
void variables_integers::set_and_make_variable(string name, int value)
{
cout << name << " " << value << endl;
cout << find_next(integer_names) << endl;
integers[find_next(integer_names)] = value;
integer_names[find_next(integer_names)] = name;
}
//*** added code ******
bool operations_and_declerations(string parsed_input[3000], variables variable)
{
if (parsed_input[0] == "int")
{
if (parsed_input[2] == "=")
{
variable.integers.set_and_make_variable(parsed_input[1], atoi(parsed_input[3].c_str()));
}
return true;
}
else if (parsed_input[0] == "string")
{
return true;
}
//else if (parsed_input[0] ==)
else
{
return false;
}
}
In operations_and_declerations(), you sent your variables parameter by value. Hence, the function created a local copy, and only modified that local copy.
You can fix the problem by sending it the parameter by reference. Just modify the function name to:
bool operations_and_declerations(string parsed_input[3000], variables & variable)
Related
My purpose is to change the tank (an object of first class) by another class (the odometer). So I try to passing by reference, its working when I pass directly object to constructor but its doesn't working when I make an object first then passing object by a method(setOdoIndex). Can someone have a way to do make a method to pass these parameters
#include <iostream>
using namespace std;
class FuelGauge {
protected:
double galls;
double check(double) const;
double checkFuel(double) const;
public:
FuelGauge(double galls){
check(galls);
this->galls = galls;
}
FuelGauge(){
*this = FuelGauge(0);
}
double getFuelLeft() const{
return galls;
}
FuelGauge operator++(){
if (galls > 15) throw "Tank max capacity is 15 gallon";
++galls;
return *this;
}
FuelGauge operator--(){
if (galls == 0) throw "Tank is empty";
--galls;
return *this;
}
void refuel(){
galls = 15;
}
};
double FuelGauge::check(double n) const {
if (n < 0) throw "Dont accepted negative value!";
if (n > 15) throw "Tank max capacity is 15 gallon";
return n;
}
class Odometer{
private:
int odo;
FuelGauge &tank;
void calOdo() {
if (odo > 999999) {odo = 0;};
}
public:
Odometer(int odo, FuelGauge &tank):tank(tank) {
this->odo = odo;
this->tank = tank;
}
Odometer():tank(tank) {
odo = 0;
}
int getOdoIndex() const{
return odo;
}
void setOdoIndex(int odo, FuelGauge &tank) {
this->odo = odo;
this->tank = tank;
}
void carDrive() {
--tank;
calOdo();
++odo;
}
};
int main() {
FuelGauge tank;
cout << "--Fill the tank--" << endl;
try {
for (int i = 0; i < 15; i++) {
++tank;
}
}
catch(const char* e) {
cerr << e << '\n';
}
cout << "\n--Car run--" << endl;
Odometer odo1(0, tank);
try {
for(int i = 0; i < 16; i++) {
cout << "Index of odometer: " << odo1.getOdoIndex() << endl;
cout << "Fuel left: " << tank.getFuelLeft() << endl;
odo1.carDrive();
}
}
catch(const char* e) {
cerr << e << '\n';
}
return 0;
}
I am writing a code using classes and am getting the wrong output, this is my function definitions:
void PrintCard(int c)
{
int Rank = c%13;
int Suit = c/13;
const char NameSuit[5] = "SCDH";
const char NameRank[14] = "23456789XJQKA";
cout << NameRank[Rank] << NameSuit[Suit];
}
CardSet::CardSet()
{
Card = NULL;
nCards = 0;
}
CardSet::CardSet(int c)
{
Card = new int[c];
for(int i = 0; i > c; i++)
{
Card[i] = (i % 52);
}
}
CardSet::~CardSet()
{
delete[] Card;
}
bool CardSet::IsEmpty() const
{
return nCards == 0;
}
void CardSet::Print() const
{
for(int i=0; i > nCards; i++)
{
PrintCard(i);
}
}
int CardSet::Size() const
{
return nCards;
}
This is my main
cout << "Testing constructors, Print(), Size() & IsEmpty():" << endl;
CardSet CardSet1; // empty cCardSet
CardSet CardSet2(12); // CardSet with 12 cards
if(CardSet1.IsEmpty()) cout<<"CardSet1 is empty"<<endl;
else cout<<"CardSet1 has "<< CardSet1.Size() <<" cards" << endl;
if(CardSet2.IsEmpty()) cout<<"CardSet2 is empty"<<endl;
else cout<<"CardSet2 has "<< CardSet2.Size() <<" cards" << endl;
cout << "Printout of CardSet1: ";
CardSet1.Print();
cout << "Printout of CardSet2: ";
CardSet2.Print();
cout << endl;
when i am compiling i am getting the correct value (0) for cardset1 however for cardset2 instead of outputting a value of 12, which is what should be the output i am getting very high numbers that are changing each time i compile. i think something is wrong with my for loops or memory allocation.
this is also what the class definition looks like:
class CardSet
{
public:
CardSet();
CardSet(int);
~CardSet();
int Size() const;
bool IsEmpty() const;
void Shuffle();
int Deal();
void Deal(int,CardSet&,CardSet&);
void Deal(int,CardSet&,CardSet&,CardSet&,CardSet&);
void AddCard(int);
void MergeShuffle(CardSet&);
void Print() const;
private:
int* Card;
int nCards;
};
any help would be greatly appreciated !!
Cheers
In CardSet::CardSet change this
for(int i = 0; i > c; i++)
to this
for (int i = 0; i < c; i++)
Also in CardSet::Print change this
for(int i=0; i > nCards; i++)
To this:
for (int i = 0; i < nCards; i++)
Finally, add nCards = c; to CardSet::CardSet.
void CardSet::Print() const
{
for(int i=0; i > nCards; i++)
{
PrintCard(i);
}
}
must be
void CardSet::Print() const
{
for(int i=0; i < nCards; i++)
{
PrintCard(i);
}
}
to correct the end test, and you have the same problem in CardSet::CardSet(int c) which must be
CardSet::CardSet(int c)
{
nCards = c;
Card = new int[c];
for(int i = 0; i < c; i++)
{
Card[i] = (i % 52);
}
}
where nCards must also be set.
In a for the test indicates if the loop continues, not if it ends
for (inits; test; changes) ...
is equivalent to
init;
while (test) {
...
changes;
}
Out of that there is no separator in PrintCard doing cout << NameRank[Rank] << NameSuit[Suit]; so may be you also need to add something like a space in Print :
void CardSet::Print() const
{
for(int i=0; i < nCards; i++)
{
PrintCard(i);
cout << ' ';
}
}
or in PrintCard to also separate the two fields like
cout << NameRank[Rank] << ' ' << NameSuit[Suit] << endl;
Note you can simplify
const char NameSuit[5] = "SCDH";
const char NameRank[14] = "23456789XJQKA";
cout << NameRank[Rank] << NameSuit[Suit];
to be
cout << "23456789XJQKA"[Rank] << "SCDH"[Suit];
Or if you really want to have the arrays I encourage you to not give a size, that avoid problems if you change the literal string and forget to also change the size, so
const char NameSuit[] = "SCDH";
const char NameRank[] = "23456789XJQKA";
For instance having :
#include <iostream>
using namespace std;
class CardSet
{
public:
CardSet();
CardSet(int);
~CardSet();
int Size() const;
bool IsEmpty() const;
void Shuffle();
int Deal();
void Deal(int,CardSet&,CardSet&);
void Deal(int,CardSet&,CardSet&,CardSet&,CardSet&);
void AddCard(int);
void MergeShuffle(CardSet&);
void Print() const;
private:
int* Card;
int nCards;
};
void PrintCard(int c)
{
int Rank = c%13;
int Suit = c/13;
cout << "23456789XJQKA"[Rank] << ' ' << "SCDH"[Suit] << endl;
}
CardSet::CardSet()
{
Card = NULL;
nCards = 0;
}
CardSet::CardSet(int c)
{
nCards = c;
Card = new int[c];
for(int i = 0; i < c; i++)
{
Card[i] = (i % 52);
}
}
CardSet::~CardSet()
{
delete[] Card;
}
bool CardSet::IsEmpty() const
{
return nCards == 0;
}
void CardSet::Print() const
{
for(int i=0; i < nCards; i++)
{
PrintCard(i);
}
}
int CardSet::Size() const
{
return nCards;
}
int main(void)
{
CardSet cs(5);
cs.Print();
}
Compilation and execution :
pi#raspberrypi:/tmp $ g++ -pedantic -Wall -Wextra c.cc
pi#raspberrypi:/tmp $ ./a.out
2 S
3 S
4 S
5 S
6 S
pi#raspberrypi:/tmp $
You should review it (the loop)
void CardSet::Print() const
{
for(int i=0; i > nCards; i++)//## reconsider it
{
PrintCard(i);
}
}
I am working on a problem that requires the implementation of two ADT's. After Implementing, I need to test my bag implementations with the following template combinations:
<int, string>-- all functions
<string, int> -- insert and find functions only
My testing so far has been entering integers to test the different functions. I do not understand what it means to test the implementations with the templates.
Here is my bagADT implementation:
#include <stdlib.h>
#include "bagADT.h"
template <typename E>
class ABag : public Bag<E> {
private:
int maxSize;
int listSize;
E* listArray;
public:
ABag(int size = defaultSize) { // Constructor
maxSize = size;
listSize = 0;
listArray = new E[maxSize];
}
~ABag() { delete[] listArray; } // Destructor
bool addItem(const E& item) {
if (listSize >= maxSize) {
return false;
}
listArray[listSize] = item;
std::cout << "Add Item: Added " << item << " in spot " << listSize << std::endl;
listSize++;
return true;
}
bool remove(E& item) {
for (int i = 0; i < listSize; i++) {
if (listArray[i] == item) {
std::cout << "Remove: Removed " << item << " from position ";
item = i;
std::cout<< item << " and adjusted the location of all other elements." << std::endl;
for (i= item; i < listSize; i++) {
listArray[i] = listArray[i + 1];
}
listSize--;
return true;
}
}
return false;
}
bool removeTop(E& returnValue) {
if (listSize == 0) {
return false;
}
else {
returnValue = listArray[listSize - 1];
std::cout << "Remove Top: Removed " << returnValue << " from the top of the stack." << std::endl;
for (int i = listSize; i < maxSize; i++) {
listArray[i] = listArray[i + 1];
}
listSize--;
return true;
}
}
bool find(E& returnValue) const {
for (int i = 0; i < (listSize - 1); i++) {
if (listArray[i] == returnValue) {
returnValue = i;
return true;
}
}
return false;
}
bool inspectTop(E& item) const {
if (listSize == 0) {
return false;
}
else {
item = listArray[listSize - 1];
std::cout << "Inspect Top: The value on top is currently " << item << "." << std::endl;
return true;
}
}
void emptyBag() {
delete[] listArray;
listSize = 0;
listArray = new E[maxSize];
std::cout << "Empty Bag: Emptied the bag." << std::endl;
}
bool operator+=(const E& addend) {
if (listSize < maxSize) {
return true;
}
return false;
}
int size() const {
std::cout << "Size: Number of elements in listArray: " << listSize << std::endl;
return (listSize - 1);
}
int bagCapacity() const {
std::cout << "Bag Capacity: The capacity of this bag is " << maxSize << std::endl;
return maxSize;
}
};
Here is another file provided by my professor called kvpairs:
#ifndef KVPAIR_H
#define KVPAIR_H
// Container for a key-value pair
// Key object must be an object for which the == operator is defined.
// For example, int and string will work since they both have == defined,
// but Int will not work since it does not have == defined.
template <typename Key, typename E>
class KVpair {
private:
Key k;
E e;
public:
// Constructors
KVpair() {}
KVpair(Key kval, E eval)
{
k = kval; e = eval;
}
KVpair(const KVpair& o) // Copy constructor
{
k = o.k; e = o.e;
}
void operator =(const KVpair& o) // Assignment operator
{
k = o.k; e = o.e;
}
bool operator==(const KVpair& o) const {
if (o.k == k) {
return true;
}
return false;
}
//The following overload is provided by Adam Morrone, Spring 2016 class.
//Thanks Adam :)
friend ostream& operator<<(ostream& os, const KVpair& o) // output print operator
{
os << "Key: " << o.k << " Value: " << o.e;
return os;
}
// Data member access functions
Key key() { return k; }
void setKey(Key ink) { k = ink; }
E value() { return e; }
};
#endif
I am expected to show the test outputs using the above templates, but I have no idea how to do this. Also, ignore the += overload. It is incorrect and I know. I am supposed to overload it to directly add a new int to the array.
I think I understand now. I could be wrong, but this is my guess.
Your bag is singly templated, but it will be holding KVpair. They said they will use KVpair with <int, string> and <string, int>.
When they talk about testing it, that means they will be instantiating it as follows:
int main() {
ABag<KVPair<int, string>> bag;
bag.addItem(KVpair(1, "hi"));
//...
}
This is what I am pretty sure they mean by "testing it with templates".
As a minor edit, I don't know what C++ version you are using but if it's very archaic, you might need to write template instantiation like ABag<KVPair<int, string> > instead of putting them together. I remember vaguely this being an issue a long time ago.
I am getting compile errors in my C++ project. On my friend's computer I get no errors but on mine I get the following:
On line 129 - "Function Definition does not declare parameters "
On line 137 - "'seats' was not declared in this scope"
I am running Code::blocks 10.05 on Windows 7.
Here is my code (with line numbers indicated by comments):
#include <iostream>
#include "Seat.h"
using namespace std;
class Plane
{
public:
int viewSeat(int sNum) {
if (seats[sNum].isFree()) {
return 0;
} else {
//cout << "Debug (Plane::viewSeat(sNum) called)";
string seatMess = "";
switch (seats[sNum].getState()) {
case 1:
seatMess = " is reserved for ";
break;
case 2:
seatMess = " has been checked in by ";
break;
}
cout << "(X) Seat ";
cout << seats[sNum].getCode();
cout << seatMess;
cout << seats[sNum].getFName() << " " << seats[sNum].getLName() << "\n";
return 1;
}
}
void viewAll() {
for (int x = 0; x < numOfSeats; x++) {
if ((seats[x].getState() == 0)) {
cout << "Seat " << seats[x].getCode() << " is free\n";
} else {
viewSeat(x);
}
}
}
void viewFree() {
int freeSeats = 0;
for (int x = 0; x < numOfSeats; x++) {
if ((seats[x].getState() == 0)) {
cout << "Seat " << seats[x].getCode() << " is free\n";
freeSeats++;
}
}
cout << "Found " << freeSeats << " free seats\n";
}
void freeSeat(int sNum) {
seats[sNum].emptySeat();
}
string getCode(int sNum) {
return seats[sNum].getCode();
}
int reserveSeat(int sNum, string fName, string lName, int age, int cType, string business = "") {
if (seats[sNum].isFree()) {
seats[sNum].setFName(fName);
seats[sNum].setLName(lName);
seats[sNum].setAge(age);
seats[sNum].setType(cType);
seats[sNum].setState(1);
seats[sNum].setBusiness(business);
return 1;
} else {
return 0;
}
}
int checkSeat(string lName, string seatCode) {
int found = 0;
for (int x = 0; x < (sizeof(seats) / sizeof(Seat)); x++) {
if ((seats[x].getCode() == seatCode) && (seats[x].getLName() == lName)) {
found = 1;
seats[x].setState(2);
return 1;
}
}
return 0;
}
int calcTake() {
int seatPrice = 5;
int totalTake, totalSeats = 0, totalWestern = 0, totalBusiness = 0, totalStandard = 0;
for (int x = 0; x < numOfSeats; x++) {
if ((seats[x].getState() != 0)) {
int cType = seats[x].getType();
int thisSeat;
if (cType == 1) {
// discount for western`
thisSeat = 0.75 * seatPrice;
totalWestern++;
} else if (cType == 2) {
// discount for business
thisSeat = 0.8 * seatPrice;
totalBusiness++;
} else {
thisSeat = 0.95 * seatPrice;
totalStandard++;
}
totalTake = totalTake + thisSeat;
totalSeats++;
}
}
return totalTake;
}
int isFree(int sNum) {
if (seats[sNum].isFree()) {
return 1;
} else {
return 0;
}
}
private:
// Line 129 ("Function Definition does not declare parameters"):
Seat seats[32] { {"1A"}, {"1B"}, {"1C"}, {"1D"},
{"2A"}, {"2B"}, {"2C"}, {"2D"},
{"3A"}, {"3B"}, {"3C"}, {"3D"},
{"4A"}, {"4B"}, {"4C"}, {"4D"},
{"5A"}, {"5B"}, {"5C"}, {"5D"},
{"6A"}, {"6B"}, {"6C"}, {"6D"},
{"7A"}, {"7B"}, {"7C"}, {"7D"},
{"8A"}, {"8B"}, {"8C"}, {"8D"}
};
// Line 137 ("'seats' was not declared in this scope"):
int numOfSeats = sizeof(seats) / sizeof(Seat);
};
I think you have missed =
Seat seats[32] = { {"1A"}, {"1B"}, {"1C"}, {"1D"},..
I have included both my definition of the Question class and its implementation, the first is a header file and the second a cpp file.
I put comments in to show where the problem is. For some reason under the constructor I can cout the questionText just fine but when I try to do this under the getQuestionText function it just outputs an empty string? Any help would be most appreciated!! Thanks!
#include <string>
#include <vector>
#include <iostream>
using namespace std;
#ifndef QUESTION_H
#define QUESTION_H
class Question{
public:
Question(int thePointValue, int theChapterNumber, \
string theQuestionText);
int getPointValue() const;
int getChapterNumber() const;
string getQuestionText() const;
virtual void writeQuestion(ostream& outfile) const;
virtual void writeKey(ostream& outfile) const;
private:
int pointValue;
int chapterNumber;
string questionText;
void writePointValue(ostream& outfile) const;
};
#endif
#include "Question.h"
Question::Question(int thePointValue, int theChapterNumber, \
string theQuestionText)
{
pointValue = thePointValue;
chapterNumber = theChapterNumber;
questionText = theQuestionText;
//HERE THIS WORKS PERFECTLY
cout << questionText << endl;
}
int Question::getPointValue() const
{
return pointValue;
}
int Question::getChapterNumber() const
{
return chapterNumber;
}
string Question::getQuestionText() const
{
//THIS IS THE PROBLEM. HERE IT OUPUTS AN EMPTY STRING NO MATTER WHAT!
cout << questionText << endl;
return questionText;
}
void Question::writeQuestion(ostream& outfile) const
{
writePointValue(outfile);
outfile << questionText << endl;
}
void Question::writeKey(ostream& outfile) const
{
writePointValue(outfile);
outfile << endl;
}
void Question::writePointValue(ostream& outfile) const
{
string pt_noun;
if (pointValue == 1)
pt_noun = "point";
else
pt_noun = "points";
outfile << "(" << pointValue << " " << pt_noun << ") ";
}
vector<Question *> QuestionsList(string filename, int min, int max)
{
vector<Question *> QuestionList;
string line;
vector<string> text;
ifstream in_file;
in_file.open(filename.c_str());
while (getline(in_file, line))
{
text.push_back(line);
}
string type;
for(int i = 0; i < text.size(); i ++)
{
int num = text[i].find('#');
type = text[i].substr(0, num);
if (type == "multiple")
{
MultipleChoiceQuestion myq = matchup(text[i]);
MultipleChoiceQuestion* myptr = &myq;
if (myq.getChapterNumber() >= min && myq.getChapterNumber() <= max)
{
QuestionList.push_back(myptr);
}
}
if (type == "short")
{
ShortAnswerQuestion myq = SAmatchup(text[i]);
ShortAnswerQuestion* myptr = &myq;
if (myq.getChapterNumber() >= min && myq.getChapterNumber() <= max)
{
QuestionList.push_back(myptr);
}
}
if (type == "long")
{
LongAnswerQuestion myq = LAmatchup(text[i]);
LongAnswerQuestion* myptr = &myq;
if (myq.getChapterNumber() >= min && myq.getChapterNumber() <= max)
{
QuestionList.push_back(myptr);
}
}
if (type == "code")
{
CodeQuestion myq = CODEmatchup(text[i]);
CodeQuestion* myptr = &myq;
if (myq.getChapterNumber() >= min && myq.getChapterNumber() <= max)
{
QuestionList.push_back(myptr);
}
}
cout << QuestionList[QuestionList.size()-1]->getQuestionText() << endl;
}
for (int i = 0; i < QuestionList.size(); i ++)
{
int numm = QuestionList.size();
cout << QuestionList[numm-1]->getQuestionText() << endl;
}
return QuestionList;
}
then when i call this in main the code breaks
vector<Question *> list = QuestionsList(pool_filename, min_chapter, max_chapter);
cout << list[0]->getQuestionText() << endl;
You are declaring, multiple times in your code, local objects and storing their pointer into the QuestionList vector (returned by the function) which, at the end of the function block, will contains dangling pointers.
MultipleChoiceQuestion myq = matchup(text[i]); // < local object
MultipleChoiceQuestion* myptr = &myq; // < pointer to local object
QuestionList.push_back(myptr); // < push back into vector
At this point you can either use dynamic memory allocation (I suggest you not to do that unless you are absolutely forced, and even in that case use one of the smart pointers provided by the standard library) or store the objects directly inside the vector.