How do I change my classes private attribute value? [closed] - c++

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 2 years ago.
Improve this question
If I use a setter, it should then change my private classes attribute's value right? However that's not the case, it's just giving me the default value of the private attribute when I use the setter. I am finding the distance travelled value with a getter.
Player.h
#pragma once
class Player
{
public:
void setForestDistanceTravelled(int amount);
int getForestDistanceTravelled();
private:
unsigned short int forestDistanceTravelled = 0;
};
Player.cpp
#include "Player.h"
void Player::setForestDistanceTravelled(int amount)
{
forestDistanceTravelled += amount;
}
int Player::getForestDistanceTravelled()
{
return forestDistanceTravelled;
}
forest.cpp
void welcomeToForest()
{
Forest forest;
Player player;
std::string userInput;
system("cls");
std::cout << "Your current distance is: " << player.getForestDistanceTravelled();
std::cin >> userInput;
if (userInput == "1")
{
unsigned short int playerDist = 0;
system("cls");
playerDist = forestDistanceRand();
player.setForestDistanceTravelled(playerDist);
welcomeToForest();
}
}

As Yksisarvinen states in the comments, the problem lays in new instances of the Player object spawning again and again with each recursion of welcomeToForest().
You just want to isolate the recursive bit of that function into its own function, that accepts the Player object as an outside parameter.
Something like below should work, whilst preserving the recursive logic of the program:
void recursiveBit(Player& player_)
{
std::string userInput;
system("cls");
std::cout << "Your current distance is: "
<< player.getForestDistanceTravelled();
std::cin >> userInput;
if (userInput == "1")
{
unsigned short int playerDist = 0;
system("cls");
playerDist = forestDistanceRand();
player_.setForestDistanceTravelled(playerDist);
recursiveBit(player_);
}
}
void welcomeToForest()
{
Forest forest;
Player player;
recursiveBit(player);
}

Related

C++ Need help getting an integer from the user and making sure it is between 2 other integers [closed]

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 4 years ago.
Improve this question
I am new to c++ and cant seem to figure out how to simply get an integer from the user and make sure it is between 0-15. Here is my code so far:
When I run the code it only prints Hello world
int main()
{
int greetAndGet();
cout << "Hello";
return 0;
}
int greetAndGet()
{
int i;
cout << "\nPlease give an integer in [1,15]" << endl;
cin >> i;
cout << endl;
}
int greetAndGet(); is a forward declaration of a function, not a call.
Write greetAndGet(); instead.
Note further that a function should be defined/declared before any call to it. So either place the function definition before main, or write
int greetAndGet(); // forward declaration
int main()
{
greetAndGet();
cout << "Hello";
return 0;
}
...
As pointed out in another answer, int greetAndGet() is a forward declaration that you probably intended to be a call; though you do want to forward declare it before main. As for testing the range of the entered value, you could use a loop to check if it is in the range. I think what you want is this:
int greetAndGet();
int main()
{
int num = greetAndGet();
cout << "Hello";
return 0;
}
int greetAndGet()
{
int i;
cout << "\nPlease give an integer in [1,15]" << endl;
do {
cin >> i;
if(i < 1 || i > 15)
{
cout << "Number not in [1,15], please try again" << endl;
}
} while(i < 1 || i > 15);
cout << endl;
return i;
}
I'm not sure what you want to do with the number, but this should get you the entered number.

Getting unusual output in simple file handling program

What is the problem with this code?
I am trying to write to a binary files MCQ type question
e.g, Question: If a computer provides database services to other, then it will be known as ? 1.Web server 2.Application 3.Database server 4.FTP server
ID: 1
Answer: 3
.
.
.
But I am getting unusual output.
Please have a look at the code I have provided comments.
The program asks for questions and write it to a binary file.
The id is automatically incremented, the question and the answer is asked from the user.
If the question is "x" then the program stops and if its anything else it asks for the answer and set all three id, question, answer to a temporary object and then write it to the file.
The program work fine for the first question & answer and then directly asks for the answer for the second answer without asking for the second question.
#include <iostream>
#include <fstream>
#include<string.h>
#include<conio.h>
using namespace std;
class questions{ //start of class
//private members
int id; //identification number for question ( 1,2,3,....)
char ques[100]; //question
int ans; //answer (1,2,3,4) MCQ
public: //public members
void displayques() //displays question
{
cout<<ques; //the same
}
int getans() //returns answer
{
return ans; //the same
}
int getid() //returns id
{
return id; //the same
}
void setques(char q[]) //set the given string in parameter to the question.
{
strcpy(ques,q);
}
void setid(int i) //set the given int as id
{
id=i;
}
void setans(int a) //set the given int as answer
{
ans=a;
}
}; //end of class questions
int main() //start of main
{
questions quesobj; //create an object of class questions
ofstream quesfile; //creates and object of class ofstream
quesfile.open("questions.dat",ios::out|ios::binary); //opens questions.dar in output mode as binary with the object quesfile of ofstream
char ask='y'; //to stop the process when its changed to n
char tempques[100]; //to temporarily store the question
int tempid=1; //to temporarily store the id, initially at 1, later is incremented
int tempans; //to temporarily store the answer
while(ask!='n') //runs upto the the point when use wants to escape the loop
{
cout<<"Question? or enter x to stop"<<endl; //asks the questions also ask if user want to escape can enter x
gets(tempques); //gets the question in temporary variable
cout<<"Question registered"<<endl; //shows question is ready to be written
if(strcmp(tempques,"x")==0) //if user enter the question as x
{
ask='n'; //sets ask to n which will end the loop
}
else //if user enters something else than x, it is considered the question
{
cout<<"Answer:"<<endl; //ask for the answer
cin>>tempans; //stores answer in temporary variable
cout<<"Answer registered"<<endl; //shows answer is ready to be written
quesobj.setid(tempid); //sets id to the temp object of the class questions
quesobj.setques(tempques); //sets question to the temp object of the class questions
quesobj.setans(tempans); //sets answer to the temp object of the class questions
quesfile.write((char *)&quesobj, sizeof(quesobj)); //write the temp object of class questions to the binary file
tempid++; //tempid is incremented for the next loop so that every question has its own id
}
} //end of while
quesfile.close(); // closes the file using the object of ofstream
}
OUTPUT:
Question? or enter x to stop
This is my first question?
Question registered
Answer:
2
Answer registered
Question? or enter x to stop
Question registered
Answer:
_
As suggested in the comments,
you should not mix C and C++ style IO.
As your code was not compiling on my system, I have cleaned your code a bit. I have tested it and its now working perfectly.
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
using namespace std;
int string_to_int(const string& str)
{
stringstream ss(str);
int str_int;
ss >> str_int;
return str_int;
}
class Question
{
int id;
string question_string;
int answer;
public:
void displayQuestion()
{
cout << question_string;
}
int getAnswer()
{
return answer;
}
int getId()
{
return id;
}
void setQuestion ( const string& question_string_)
{
question_string = question_string_;
}
void setId ( int id_ )
{
id = id_;
}
void setAnswer ( int answer_ )
{
answer = answer_;
}
};
int main()
{
Question question;
ofstream question_file;
question_file.open ( "questions.dat", ios::out | ios::binary );
char option = 'y';
string temp_question;
int temp_id =1;
int temp_answer;
while ( option != 'n' )
{
cout << "Question? or enter 'x' to stop" << endl;
getline(cin, temp_question);
cout << "Question registered" << endl;
if (temp_question == "x")
{
option = 'n';
}
else
{
cout << "Answer? :" << endl;
string temp_answer_string;
getline(cin, temp_answer_string);
temp_answer = string_to_int(temp_answer_string);
cout << "Answer registered" << endl;
question.setId ( temp_id );
question.setQuestion ( temp_question );
question.setAnswer ( temp_answer );
question_file.write ( ( char* ) &question, sizeof ( question ) );
temp_id++;
}
}
question_file.close();
}

C++ object oriented problems [closed]

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 8 years ago.
Improve this question
This is an assignment i am trying to figure out:
Create a new project named Project3 and create a class named Rover
Within the Rover class, specify the following member instance variables:
name(string)
x position on a grid (integer)
y position on a grid (integer)
direction by compass – N, S, E, or W (String)
speed (0 – 5 meters per second, integer)
Within the Rover class, specify the following methods:
Default constructor – set the rover’s position to (0,0), its speed to 0, its direction to
North.
Constructor that receives parameters to initialize all five instance variables described above
Setter methods for each instance variable
Getter methods for each instance variable
getRoverData – returns a string that displays values for each instance variable of the
current rover object, placing each value on a separate line, as follows:
Rover name: A
X-position: 0
Y-position: 0
Direction: E
Speed: 1
Create a class client (main) that creates an array of the a maximum of five rovers and gets the initial
values for all rovers from the user. After the user specifies values for each rover, display a summary
of the rover’s values as shown above.
I have about a billion errors and i dont know why.
using namespace std;
class Rover {
private:
string name;
int x;
int y;
string direction;
int speed;
int position[10][10];
public:
void Rover();
void constructor(string name, int x, int y, string direction, int speed);
void setName(string name);
void setX(int x);
void setY(int y);
void setDirection(string direction);
void setSpeed();
string getName();
int getX();
int getY();
string getDirection();
int getSpeed();
string getRoverData();
};
void Rover::Rover() {
r1.position[0][0];
r1.speed = 0;
r1.direction = "N";
}
string Rover::getRoverData() {
cout << "Rover name: " << r1.getName() << endl;
cout << "X-position: " << r1.getX() << endl;
cout << "Y-position: " << r1.getY() << endl;
cout << "Direction: " << r1.getDirection() << endl;
cout << "Speed: " << r1.getSpeed() << endl;
}
void Rover::constructor(string name1, int x1, int y1, string direction1, int speed1) {
r1.name = name1;
r1.x = x1;
r1.y = y1;
r1.direction = direction1;
r1.speed = speed1;
}
void Rover::setName(string name) {
r1.name = name;
}
void Rover::setX(int x) {
r1.x = x;
}
void Rover::setY(int y) {
r1.y = y;
}
void Rover::setDirection(string direction) {
r1.direction = direction;
}
void Rover::setSpeed(int speed) {
r1.speed = speed;
}
string Rover::getName() {
return name;
}
int Rover::getX() {
return x;
}
int Rover::getY() {
return y;
}
string Rover::getDirection() {
return direction;
}
int Rover::getSpeed() {
return speed;
}
int main(int argc, char** argv) {
string name;
int x;
int y;
string direction;
int speed;
Rover r1;
r1.constructor("Yoda", 3, 3, "N", 3);
cout << "Enter name for Rover: ";
cin >> name;
r1.setName(name);
cout << "Enter its x position: ";
cin >> x;
r1.setX(x);
cout << "Enter its y position: ";
cin >> y;
r1.setY(y);
cout << "Enter direction N,E,S,W: ";
cin >> direction;
r1.setDirection(direction);
cout << "Enter its speed: ";
cin >> speed;
r1.setSpeed(speed);
r1.getRoverData();
return 0;
}
Your example appears incomplete. I'm guessing you just missed including the following lines in your post
#include <string>
#include <iostream>
using namespace std;
First, constructors do not have a return type so void Rover(); makes no sense. Remove void and you're golden there.
Second, what exactly do you think r1 is supposed to be? The compiler should tell you the identifier is undefined because it isn't. remove r1. from your member functions (i.e. anything function starting with Rover::. and you're golden there.
Third, what do you think r1.position[0][0] is going to do? It's just an expression that does nothing. Even position[0][0] is not going to do anything. Perhaps you want to initialize the array somehow but you haven't provided enough information to determine what you're trying to accomplish with it.
Fourth, the member function void Rover::setSpeed(int) has not been declared within the Rover class. Did you forget something? Based on your code it should be
int Rover::getSpeed()
{
return speed;
}
Fifth, void Rover::setSpeed(); doesn't make much sense unless it actually accepts an argument.

Very weird behaviour with my C++ vector [closed]

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 8 years ago.
Improve this question
I've been debugging this for a long time now - but I have no clue what the issue is.
I get a name from the console (via std::cin) and then proceed to create a new Player object with it. Then I pass the new object to the Gameboard to be added to a std::vector<J> where J is part of a template. Here's the code:
main.cpp
Gameboard<Tile,Player,5,5> board = Gameboard<Tile,Player,5,5>();
std::string name;
std::cout << "Enter a name: "
std::cin >> name;
board.setPlayer(Player(name));
std::cout << std::endl;
std::cout << "Enter a name: "
std::cin >> name;
board.setPlayer(Player(name));
std::cout << std::endl;
std::cout << "Enter a name: "
std::cin >> name;
board.setPlayer(Player(name));
gameboard.h
template<class T, class J, const int X, const int Y>
class Gameboard {
std::vector<J> players;
public:
void setPlayer(J player);
};
template<class T, class J, const int X, const int Y>
void Gameboard<T,J,X,Y>::setPlayer(J p) {
////// DEBUG CODE //////
std::cout << p.getName() << std::endl;
players.push_back(p);
for (int i = 0; i < players.size(); i++) {
std::cout << players.at(i).getName() << std::endl;
}
}
player.h/player.cpp
class Player {
std::string name;
public:
Player(std::string _name);
std::string getName();
};
Player::Player(std::string _name) {
name = _name;
}
std::string Player::getName() {
return name;
}
I think I've tracked my problem down to the code marked DEBUG CODE. Using the above code, and entering the names Bob, Joe, and Tim, I would get the following output:
Enter a name: bob
bob
Enter a name: joe
joe
Enter a name: tim
tim
[exit]
So somehow, when I add the player to the vector, it becomes corrupted or something similar. The object is valid right before insertion because I echo out the name. The vector is also growing in size because it's printing blank lines equal to the number of players added.
What is going on?
You might have a copy constructor where you are not copying the name. So when you push_back on the vector, a Player object with empty name gets pushed on the vector.
Implement the copy constructor properly and it should work

Whenever i use cin and use spaces in the string, why does it just skip through the whole thing? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I made a program that should take input print it. Then run a simple addition thing but when i use spaces in the input it skips through the addition. I do not know what the problem is.
this is the class stuff
#include <iostream>
#include <string>
using namespace std;
class Cheese {
private:
string name;
public:
void setName(string x){
cin >> x;
x = name;
}
string getName(){
return name;
}
void print(){
cout << name << endl;
}
};
this is the main stuff
int main()
{
string h;
Cheese hole;
hole.setName(h);
hole.getName();
hole.print();
this part is getting skipped through without letting me input
int x = 5;
int y = 16;
cout << x+y;
num(x);
int a;
int b;
int c;
cout << "Type in a number and press enter.";
cin >> a;
cout << "Repeat.";
cin >> b;
c = a+b;
cout << c << endl;
if(c <= 21){
cout << "Good job!";
}
else {
cout << "You fail!";
}
return 0;
}
I suggest you divide the responsibilities a little differently. The Cheese class's setName function should simply take a string and set the instance's member variable to the given argument.
Then your program can read from standard input and populate a string within main, and pass that string to setName.
To be more concrete:
class Cheese {
private:
string name;
public:
void setName(const string& x){
// change this code to set the 'name' member variable
}
[...]
};
And the main becomes:
int main()
{
string h;
Cheese hole;
std::string input_name;
cout << "Type a name and press enter.";
cin >> input_name; // Will read up to first whitespace character.
hole.setName(input_name);
hole.getName(); // this is a no-op: compiler may warn of unused return value
hole.print();
In general, reading standard input as part of a class's interface is a bad idea, because it makes it hard to re-use that class in the future (for example, with programs that take input from a file instead of from a human at a console).
The input that you pass to cin input stream skips any white space, Tab space or newline. If you wish to input string then you can use cin.getline(string s). The input after the white space gets passed to next waiting cin, as the next cin accepts integer and it get a character string it skips that. Thus when enter a string with white spaces the program skips the remaining part.