Class private member wont change in function - c++

using namespace std;
class map
{
private:
float result= 0;
public:
void func_1();
void setres(float counter);
float getres();
};
void map::setres(float counter)
{
result= counter;
}
float map::getres()
{
return result;
}
void map::func_1()
{
float num_0=0, num_1=0, sum=0, i;
map run;
cout << run.getres() << " Result." << endl;
if(result != 0)
cout << "We already have a result saved and it's: " << run.getres() << endl;
else
{
cout << "Give me first number: ", cin >> num_0;
cout << "Give me second number: ", cin >> num_1;
sum= num_0+num_1;
cout << "Result is: " << sum << endl;
}
cout << "The program will save the result." << endl;
run.setres(sum);
cout << "The saved result is: " << run.getres() << "\nPress 1 to repeat the function and check\nif the result is saved." << endl;
cin >> i;
if(i==1)
run.func_1();
}
int main()
{
map go;
go.func_1();
return 0;
}
I don't know why the private variable result is not saved. And how can i make it work.
Then i start compiling it works fine, private result is changing, but then i reopen the function, the result is back to 0 and i wanted it ro be the last result.
Example:
I put 4
I put 7
Sum is 11
And saved result is 11
Then i press 1 to go to the start the result is 0 again, but i wanted it to be 11 not 0.

Within the function you are creating a local variable of the type map
map run;
the data member result of which is changed. That is the function does not change the data member result of the object for which the function is called.
Moreover for example in this code snippet
cout << run.getres() << " Result." << endl;
if(result != 0)
you are accessing the data member result of two different object. In the first statement
cout << run.getres() << " Result." << endl;
you are accessing the data member of the local object run while in the next statement
if(result != 0)
you are accessing the data member result of the object (the object go declared in main) for which the member function is called.
So remove the declaration in the function
map run;
and instead of expressions like for example run.getres() use either just getres() or this->getres().

The issue is that your function is not using members of the object the method is called on. Instead you create a new instance inside the function:
void map::func_1()
{
float num_0=0, num_1=0, sum=0, i;
map run; // <---------- here
//...
Thats why every time you call the function you get a new fresh object. You do not need to create that instance. You already create one in main and inside the member functions you can access its members. As a fix you can remove all run. from the code. Eg
cout << run.getres() << " Result." << endl;
->
cout << getres() << " Result." << endl;
or if you prefer
cout << this->getres() << " Result." << endl;

The value is saved to run, and run.func_1() is called for checking, but then run.getres() is called there. This run is new map object and differ from the run in which the data is saved.
You checked result != 0, but you used run.getres() to print the result. Inconsisitency here.
Instead of
cout << run.getres() << " Result." << endl;
if(result != 0)
cout << "We already have a result saved and it's: " << run.getres() << endl;
You should do
cout << result << " Result." << endl;
if(result != 0)
cout << "We already have a result saved and it's: " << result << endl;
or
cout << getres() << " Result." << endl;
if(getres() != 0)
cout << "We already have a result saved and it's: " << getres() << endl;

Related

float vector and pointer returns different values even though they have same adress

I have a class which returns vector<vector<float>> with its getTemplates() function. My code is as follows for this case:
cout << "Get [0][0] " << s.getTemplates()[0][0] << endl;
cout << "vec addr " << &(s.getTemplates()[0][0]) << endl;
float *embFloat = s.getTemplates()[0].data();
cout << "embFloat: " << embFloat << endl;
cout << "*embFloat " << *embFloat << endl;
cout << "embFloat[0] " << embFloat[0] << endl;
and the output is as follows:
Get [0][0] 0.00191223
vec addr 0x555557973280
embFloat: 0x555557973280
*embFloat -8.71571e+33
embFloat[0] -8.71571e+33
I expect embFloat[0] and s.getTemplates()[0][0] to return exactly same value. What am I missing here?
s.getTemplates() returns a temporary which (in this particular instance) goes out of scope at the end of the statement that contains it.
float *embFloat is therefore a dangling pointer - i.e. it's pointing to an object that no longer exists.

Selecting an array value using a random number generator

its a text based monopoly game where i need the dice to select the number from the array like on a board.
I have the number generator, what i need to do though is when the value comes up it pluses it on the array to get the matching number so for example if the players rolls a 6, the 6 + array 0 = array value 6 which will be a name of a street but it means the player knows which place on the made up board they are on. here is the coding i am using to try and do so but i keep on getting 006ff65 what ever. i how can i get it for showing just the number as the names will be added later.
{
int main()
{
int number = 12;
int rnum = (rand() % number) + 1;
int house = 1;
int moneyscore = 10000;
double values[] = {
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40 };
char name[50];
cout << "Who are you, Dog, Car, Hat or Bus" << endl;
cin.getline(name, 50);
cout << "Welcome to Our Game " << name << " You have " << moneyscore << " .PLease Roll dice to get started" << endl;
cout << "\n----------------------Press any Enter to roll dice----------------------" << endl;
system("cls");
int choiceOne_Path;
cout << "# You roll a " << rnum << endl;
rnum = values[rnum];
cout << "# you have " << moneyscore << endl;
cout << "# You move to grid "<< values << endl;
cout << "\t >> Enter '1' Buy Property" << endl;
cout << "\t >> Enter '2' Recieve Rent" << endl;
cout << "\t >> Enter '3' End turn" << endl;
retry:
cout << "\nEnter your choice: ";
cin >> choiceOne_Path;
if (choiceOne_Path == 1)
{
cout << "\n Buy Property " << endl;
cout << " " << name << " has " << moneyscore << endl;
cout << " " << house <<" House has been placed by " << name <<" who spent 2,500" << endl;
moneyscore -= 2500;
cout << " " << name << " now has " << moneyscore << endl;
cout << "\n Roll again" << endl;
cout << "# You roll a " << rnum << endl;
}
else if (choiceOne_Path == 2)
{
cout << "\n You recieved 2500 from rent" << endl;
moneyscore += 2500;
cout << " " << name << "\n now has" << moneyscore << endl;
cout << "\n(Player will gain money form house, will need to find a way in order to make the
console remember what score == to postion)" << endl;
cout << "Ends turn" << endl;
}
else if (choiceOne_Path == 3)
{
cout << "\n Roll again" << endl;
cout << "# You roll a " << rnum << endl;
}
else
{
cout << "You are doing it wrong, player! Press either '1' or '2', nothing else!" << endl;
goto retry;
}
cout << "\n----------------------Press any key to continue----------------------" << endl;
_getch();
}
}
As far as I know, you should use srand (time(NULL)); between every call to rand() to correctly return a new random number from every call.
"srand" initialize the random number generator using a seed. In this case seed is time, which should be different on every call.
Pretty basic. You either made a few typos or need to learn how arrays work (and program flow, and subroutines, but perhaps that is for later lessons.)
First you are assigning the result of the array lookup back into your random number: rnum = values[rnum]; which is not a big deal except you use that variable later and it no longer contains what you may think it does. It actually contains the value you are looking for!
Second the variable values is a pointer to the head of your array so you are outputting the address of the values array with this line: cout << "# You move to grid "<< values << endl; there is no array look up happening at all here. It is strange you missed that because you did reference the array contents properly when you replaced the random number value earlier.

C++ function missing after change in main

Just for clarification, currently using Repl.it. If this problem is due to Repl.it, that'll be it.
I am trying to make multiple state machines that influence each other through different states (Happy, Sad, or Mad). Each machine can talk: say what state they're in; or interact with a different machine, thus changing one of the machine's states;
The problem I have with my code is the everyone function, allowing every state machine in an array to say their states. Whenever something is changed in the main function, the everyone function just doesn't run anymore. I'm sorry that this post is really long, mostly due to any omissions causes the function to break.
This is my code:
using namespace std;
enum Mood {Happy, Sad, Mad, Default};
class StateMac {
Mood state; //The machine's current state
/* Other methods no shown */
//Returns a string relative to their current state
string talk() {
switch(state) {
case Happy : return "I'm happy!";
case Sad : return "I'm sad...";
case Mad : return "I'm Mad!!!";
case Default : return "...";
}
}
//Compares the states between two machines
bool compare(StateMac aStateMachine) {
if (state == aStateMachine.getState()) {
return true;
}
return false;
}
};
//Gets size of a state machine array by comparing each to a default machine
int getSMarSize(StateMac SMar[]) {
int counter = 0;
for (int i = 0; i < 100; i++) {
if (SMar[i].compare(StateMac())) {
break;
} else {
counter += 1;
}
}
return counter;
}
//Receives an array of state machines and makes each of them say their states,
void everyone(StateMac SMar[]) {
for (int i; i < getSMarSize(SMar); i++) {
cout << "SM" << i << ": " << SMar[i].talk() << endl;
}
}
int main() {
//Array with 4 state machines
StateMac ar[] = {StateMac(Happy), StateMac(Sad), StateMac(Mad), StateMac()};
//Have everyone say their states
everyone(ar);
//Does same as above but line-by-line for each machine
cout << "SM0: " << ar[0].talk() << endl;
cout << "SM1: " << ar[1].talk() << endl;
cout << "SM2: " << ar[2].talk() << endl;
//Other functions
string response = ar[0].interact(&ar[2]);
cout << "SM0 to SM1: " << response << endl;
cout << "SM1: " << ar[1].talk() << endl;
response = ar[0].interact(&ar[2]);
cout << "SM0 to SM2: " << response << endl;
cout << "SM2: " << ar[2].talk() << endl;
response = ar[1].interact(&ar[2]);
cout << "SM0 to SM2: " << response << endl;
cout << "SM0: " << ar[0].talk() << endl;
cout << "SM1: " << ar[1].talk() << endl;
cout << "SM2: " << ar[2].talk() << endl;
}
Producing this result:
SM0: I'm happy! //From everyone function
SM1: I'm sad...
SM2: I'm Mad!!!
SM0: I'm happy! //From line-by-line
SM1: I'm sad...
SM2: I'm Mad!!!
SM0 to SM1: There's nothing to be mad about! //Other functions
SM1: I'm sad...
SM0 to SM2: That guy!!!
SM2: I'm happy!
SM0 to SM2: You look happy, might as well forget about that.
SM0: I'm Mad!!!
SM1: I'm sad...
SM2: I'm happy!
Everything looks good in the result as of now. However, if I am to add, change, or delete any line in the main function, all of a sudden, the everyone function doesn't run anymore.
For example, I changed one of the responses in the main function:
everyone(ar);
cout << "SM0: " << ar[0].talk() << endl;
cout << "SM1: " << ar[1].talk() << endl;
cout << "SM2: " << ar[2].talk() << endl;
string response = ""; //Changed here
cout << "SM0 to SM1: " << response << endl;
cout << "SM1: " << ar[1].talk() << endl;
response = ar[0].interact(&ar[2]);
cout << "SM0 to SM2: " << response << endl;
cout << "SM2: " << ar[2].talk() << endl;
response = ar[1].interact(&ar[2]);
cout << "SM0 to SM2: " << response << endl;
cout << "SM0: " << ar[0].talk() << endl;
cout << "SM1: " << ar[1].talk() << endl;
cout << "SM2: " << ar[2].talk() << endl;
Creating this result, notice the missing everyone function call:
SM0: I'm happy! //Line-by-line
SM1: I'm sad...
SM2: I'm Mad!!!
SM0 to SM1: //Changed response
SM1: I'm sad...
SM0 to SM2: There's nothing to be mad about!
SM2: I'm happy!
SM0 to SM2: You look happy, might as well forget about that.
SM0: I'm happy!
SM1: I'm sad...
SM2: I'm happy!
The problem is in your function
void everyone(StateMac SMar[]) {
for (int i; i < getSMarSize(SMar); i++) {
cout << "SM" << i << ": " << SMar[i].talk() << endl;
}
}
This code does not initialize the variable i, and so it has undefined behavior. Changing this to int i = 0 should solve your problem.
BTW, I am also puzzled by your use of the function int getSMarSize(StateMac SMar[]) to determine the size of the array of state machines. Your strategy seems to be to leave a "blank" state machine at the end of the array and counts the array length by iterating until it finds this blank state machine, much like the terminating character in a C string. Since you cannot automatically enforce that the array should end in StateMac(), unlike C/C++ can do with a C string, this is error-prone. There is no good reason to use this technique for an array in C++ -- you should either pass the length of the array as a parameter to the function, or better yet use the std::vector container.

C++ assignment help on creating codes for reusability?

I've been having trouble doing this assignment. I'm just having a hard time understanding and I am not entirely sure what to do. I've researched and watched videos and havent been able to find the right, specific information. Its a bunch of questions, so I hope someone can not only giveme the answers, but also explain to me so I have a strong understanding :) . Here are the questions:
1)In this exercise we have been given some program code that will accept two integers as inputs
and evaluate which one holds the larger value. This evaluation occurs in multiple places
throughout the code. Write a function that the program could use to perform this same evaluation
instead of duplicating the code over and over. Start by writing a suitable function declaration
towards the beginning of the code file. You will have to decide whether your function will return
some output or not.
2) With your declaration written proceed to define the function, including the appropriate pieces of
code that will evaluate which of the two integers is the largest. If you stated earlier that your
function will return a value, be sure to define what it will return here.
3) Use your result from parts (1) and (2) to reduce the amount of duplicate code in the main function
provided by replacing the multiple instances of the integer comparison with a call to invoke the
function you have created. Remember that the function will require two integers to be passed in
as arguments and if you are returning some value from the function it should be used (stored in
a variable, outputted to screen, etc.). As a word of advice, test your function works correctly after
replacing just one of the evaluations, don’t replace them all at once (if the function works correctly
for the first replacement then it should work for the others).
4) Since the function you have created only compares the values of its parameters and doesn’t write
to them (i.e. change the value stored in them) we should specify in the function declaration and
definition that these parameters should be treated like constants. Make the necessary
modifications to the function and test again to verify the function still works. Confirm the function
will not let you change the data of the parameters by trying to include an operation in the function
that would change the value of one of the variables (e.g. number2 += 10;)
-- Here is the code ( I apologise for the long writing):
#include <iostream>
int main(void)
{
using std::cout;
using std::cin;
using std::endl;
int nNum1 = 10, nNum2 = 11;
cout << "This program will compare two numbers and report which one is larger.\n\n"
<< "Proceeding with evaluation...\n" << endl;
cout << "\nUsing numbers: " << nNum1 << " and " << nNum2 << ", the larger one is: ";
if (nNum1 > nNum2)
cout << nNum1 << endl;
else if (nNum1 < nNum2)
cout << nNum2 << endl;
else
cout << "Neither of them! It's a draw." << endl;
int numberA = 234;
int numberB = 234;
cout << "\nUsing numbers: " << numberA << " and " << numberB << ", the larger one is: ";
if (numberA > numberB)
cout << numberA << endl;
else if (numberA < numberB)
cout << numberB << endl;
else
cout << "Neither of them! It's a draw." << endl;
int one = 'a';
int two = 'A';
cout << "\nUsing numbers: " << one << " and " << two << ", the larger one is: ";
if (one > two)
cout << one << endl;
else if (one < two)
cout << two << endl;
else
cout << "Neither of them! It's a draw." << endl;
cout << "\nUsing numbers: " << 13 << " and " << 84 << ", the larger one is: ";
if (13 > 84)
cout << 13 << endl;
else if (13 < 84)
cout << 84 << endl;
else
cout << "Neither of them! It's a draw." << endl;
int input1 = 0;
int input2 = 0;
cout << "\nPlease enter a number: ";
cin >> input1;
cout << "\nPlease enter a second number: ";
cin >> input2;
cout << "\nUsing numbers: " << input1 << " and " << input2 << ", the larger one is: ";
if (input1 > input2)
cout << input1 << endl;
else if (input1 < input2)
cout << input2 << endl;
else
cout << "Neither of them! It's a draw." << endl;
cout << "\n\tThank you for running me :3\n" << endl;
return 0;
}
You basically have to refactor the code to replace the duplicate code part in your main function.
If you look closely you will see that code like this repeats:
cout << "\nUsing numbers: " << nNum1 << " and " << nNum2 << ", the larger one is: ";
if (nNum1 > nNum2)
cout << nNum1 << endl;
else if (nNum1 < nNum2)
cout << nNum2 << endl;
else
cout << "Neither of them! It's a draw." << endl;
So put that into a function:
void CompareNumbers(int nNum1, int nNum2)
{
cout << "\nUsing numbers: " << nNum1 << " and " << nNum2 << ", the larger one is: ";
if (nNum1 > nNum2)
cout << nNum1 << endl;
else if (nNum1 < nNum2)
cout << nNum2 << endl;
else
cout << "Neither of them! It's a draw." << endl;
}
And call this in your main function instead of duplicating the said code block.

error: no matching function for call to 'Stack<int>::Peek()'

I keep getting the following error: error: no matching function for call to 'Stack::Peek()'
I am new to C++ and I cannot figure out why I am getting the error
This is my Peek() function.
int Peek(T data)
{
if(IsEmpty ())
return -1;
else
return top -> data;
}
and this is my main() function.
int main()
{
Stack<int> s1;
cout << "*declare stack s1\ns1=" << s1 << endl; // stack initially set to 0
cout << "s1.Size()=" << s1.Size() << endl;
cout << "s1.IsEmpty()=" << ((s1.IsEmpty()) ? "T" : "F") << endl;
cout << "s1.IsFull()=" << ((s1.IsFull()) ? "T" : "F") << endl;
cout << "s1.Peek()=" << s1.Peek() << endl;
cout << endl;
Stack<char> s4;
for (char c='a'; c<='z'; c++)s4.Push(c);
cout << "s4=" << s4 << endl;
cout << "s4.Size()=" << s4.Size() << endl;
cout << "s4.IsEmpty()=" << ((s4.IsEmpty()) ? "T" : "F") << endl;
cout << "s4.IsFull()=" << ((s4.IsFull()) ? "T" : "F") << endl;
cout << "s4.Peek()=" << s4.Peek() << endl;
}
I get the error whenever the Peek function is called in main so I was wondering if anyone could help me with this.
You defined a Peek method, but not Stack::Peek. Your method should have this signature: int Stack::Peek(T data)
Because you are calling it without any argument. Your declaration:
int Peek(T data)
Your invocation:
s4.Peek()
Indeed a stack data type doesn't need an argument to the peek function (nor you use it). You should modify your original function to int Peek().
Your function Peak is declared as having one parameter
int Peek(T data);
However you call it without any argument
cout << "s1.Peek()=" << s1.Peek() << endl;
So the compiler does not know a function with name Peak that has no parameter.