Im new to classes and i have to write my own functions and variables in a class that stores rover information when it is entered and for some reason whenever I write my functions and try to call them in main they are not working. I have provided my code and Im wondering if someone can help me explain how to get the rovers data to be stored for each rover r1-r5. Thank you.
class Rover{
private:
string name;
int xpos;
int ypos;
string direction; //Use Cardinal Directions (N,S,E,W)
int speed; //(0-5 m/sec)
public:
//Constructors
//defaultRover();
//Rover();
//Get functions
string getName();
int getXpos();
int getYpos();
string getDirect();
int getSpeed();
void getRoverData();
//Set functions
string setName();
void setXpos();
void setYpos();
void setDirect();
void setSpeed();
};
//Constructor function
/*Rover::defaultRover()
{
xpos=0;
ypos=0;
direction="N";
speed=0;
}
*/
/*
Rover::Rover()
{
cout<<"Please enter the starting X-position: ";
cin>>xpos;
cout<<"Please enter the starting Y-position: ";
cin>>ypos;
cout<<"Please enter the starting direction (N,S,E,W): ";
cin>>direction;
cout<<"Please enter the starting speed (0-5): ";
cin>>speed;
cout<<endl;
}
*/
//Getter functions
string Rover::getName()
{
return name;
}
int Rover::getXpos()
{
return xpos;
}
int Rover::getYpos()
{
return ypos;
}
string Rover::getDirect()
{
return direction;
}
int Rover::getSpeed()
{
return speed;
}
void Rover::getRoverData()
{
cout<<name;
cout<<xpos;
cout<<ypos;
cout<<direction;
cout<<speed;
}
//Setter functions
string Rover::setName()
{
cout<<"Please enter the Rover name ";
cin>>name;
}
void Rover::setXpos()
{
cout<<"Please enter the X-position of the Rover ";
cin>>xpos;
}
void Rover::setYpos()
{
cout<<"Please enter the Y-position of the Rover ";
cin>>ypos;
}
void Rover::setDirect()
{
cout<<"Please enter the direction of the Rover (N,S,E,W) ";
cin>>direction;
}
void Rover::setSpeed()
{
cout<<"Please enter the speed of the Rover (0-5) ";
cin>>speed;
}
int main(int argc, char** argv)
{
Rover r1, r2, r3, r4, r5;
r1.setName();
r1.getName();
return 0;
}
As a general rule...
getters and setters should not communicate with stdin or stdout
getters should return what they're getting
setters should assign the member to what is being passed in
Let's make a pretend class Foo:
class Foo {
public:
// setters
void set_bar(int bar) { bar_ = bar; }
void set_baz(std::string baz) { baz_ = baz; }
void set_boo(double boo) { boo_ = boo; }
// getters
int get_bar() const { return bar_; }
std::string get_baz() const { return baz_; }
double get_boo() const { return boo_; }
private:
int bar_;
std::string baz_;
double boo_;
};
The way this should be used is something like this:
Foo foo;
int bar;
std::cout << "Please enter bar: " << std::endl;
std::cin >> bar;
foo.set_bar(bar);
std::cout << "foo's bar is " << foo.get_bar() << std::endl;
You need to change a lot of code, but I hope this helped.
Related
It has two issues
1). program is not taking input it exits without getting value of variable option.
2).Also my base and derived class are not initializing they are displaying garbage value.
Here is complete code.
#include<iostream>
using namespace std;
class BeverageItem
{
protected:
string name;
double price;
public:
void set_name(string n);
string get_name();
void set_price(double pr);
double get_price();
};
void BeverageItem::set_name(string n)
{
name=n;
}
string BeverageItem::get_name()
{
return(name);
}
void BeverageItem::set_price(double pr)
{
price=pr;
}
double BeverageItem::get_price()
{
return(price);
}
class HotBeverage:public BeverageItem
{
private:
int tea_bags;
int whiteners;
public:
//HotBeverage(int bg,int wht);
void set_teabags(int t_bags);
int get_teabags();
int getwhiteners();
void set_whiteners(int wht);
double basePrice();
double computeTax();
double totalCost();
void print();
};
double HotBeverage::computeTax()
{
return (0.16*price);
}
double HotBeverage::totalCost()
{
return(price+computeTax());
}
double HotBeverage::basePrice()
{
double pr;
if((tea_bags==1)&& (whiteners==1))
{
pr=20;
}
else if((tea_bags>1)&& (whiteners>1))
{
tea_bags=tea_bags-1;
pr=20+(5*tea_bags);
}
set_price(pr);
return(pr);
}
void HotBeverage::set_teabags(int t_bags)
{
tea_bags=t_bags;
}
int HotBeverage::get_teabags()
{
return(tea_bags);
}
int HotBeverage::HotBeverage::getwhiteners()
{
return(whiteners);
}
void HotBeverage::set_whiteners(int wht)
{
whiteners=wht;
}
void HotBeverage::print()
{
cout<<"Name: "<<name<<endl;
cout<<"Tax:"<<computeTax()<<endl;
cout<<"Total Cost: "<<totalCost()<<endl;
}
class ColdBeverage:public BeverageItem
{
private:
int drinkSize;
public:
//ColdBeverage(int drinkSize);
void setDrinkSsize(int sz);
int getDrinkSize();
double basePrice();
double computeTax();
double totalCost();
void print();
};
void ColdBeverage::print()
{
cout<<"Name: "<<name<<endl;
cout<<"Tax:"<<computeTax()<<endl;
cout<<"Total Cost: "<<totalCost()<<endl;
}
void ColdBeverage::setDrinkSsize(int sz)
{
drinkSize=sz;
}
int ColdBeverage::getDrinkSize()
{
return(drinkSize);
}
double ColdBeverage::computeTax()
{
return (0.16*price);
}
double ColdBeverage::totalCost()
{
return(price+computeTax());
}
double ColdBeverage::basePrice()
{
double pr;
double regularPr=30;
switch(drinkSize)
{
case 1: //regular,
pr=regularPr;
break;
case 2: //large.
price=1.5*regularPr;
break;
case 3: //extra large.
price=2*regularPr;
break;
}
set_price(pr);
return(pr);
}
int main()
{
string name;
int option;
cout<<"Enter The Beverage Name=";
cin>>name;
cout<<"1. For Hot Beverage\n\n";
cout<<"2. For Cold Beverage\n\n";
cout<<"Select Your Choice(1,2)=";
cin>>option;
BeverageItem bi;
bi.set_name(name);
**//some other code here.**
return 0;
}
1) I don't really see a problem with the compiler i tried with
http://cpp.sh/4p5mw
2) POD's in member variables are not default initialised.
https://stackoverflow.com/a/15212447/4669663
Here was the issue
cin>>name;
cin stops when whitespaces are entered in a string so I would have to use
getline(cin,name);
Second issue was because i was not calling the basePrice() before print()
thanks to everyone
I need to creat an object Pokemon in the main()
that assign it into the class PokemonWorld, and let the PokemonWolrd to decide which PokemonStation is this Pokemon need to go
I tired get the data separatly (get name and hp) and get together(get a Pokemon class)
but both fail
#include <iostream>
#include <cstring>
#include <iomanip>
using namespace std;
class Pokemon {
public:
Pokemon() {};
Pokemon(char x[], int n) {
strncpy_s(name, x, 10);
hp = n;
};
private:
char name[10];
int hp;
};
class PokemonStation {
private:
Pokemon **list= new Pokemon*[1000];
public:
PokemonStation() {};
PokemonStation(int x) {
id = x;
};
int id;
void assigntoList(int i,Pokemon x)
{
if (i > 0)
i--;
list[i] = new Pokemon(x);
cout << "creat" << list[i];
};
};
class PokemonWorld {
private:
char name[10];
public:
PokemonStation s1;
PokemonStation s2;
PokemonWorld() {};
PokemonWorld(char x[], int y=1, int z=2) {
strncpy_s(name, x, 10);
PokemonStation s1(y);
PokemonStation s2(z);
};
const char* const getName() const{
return name;
};
void assigntoStation(int i,Pokemon x) {
if (i == 0 || i % 2 == 0)
s1.assigntoList(i, x);
else
s2.assigntoList(i, x);
};
};
void main() {
int number,hp,i;
char name[10];
cout << "What is the World Name ?" <<endl;
cin >> name;
PokemonWorld world(name);
cout << "Please input the number of Pokemon in the " << world.getName() <<" world:" << endl;
cin >> number;
Pokemon **mon = new Pokemon*[number];
cout << "Please input the characteristics of all Pokemon: Name HP" << endl;
for (i = 0;i < number;i++)
{
cin >> name >> hp;
mon[i] = new Pokemon(name, hp);
world.assigntoStation(i,*(mon[i]));
}
for (i = 0;i < number;i++)
cout << "world is " << world.getName() << endl;
system("pause");
};
In C++, you should use std::vectors for dynamic lists of things and std::strings for text. If you know Java, these are like ArrayList and String. (To use these, make sure you #include <vector> and <string>.)
For instance, your Pokemon class, rewritten with name as a string:
class Pokemon {
public:
Pokemon() {}
Pokemon(string name, int hp):name(name), hp(hp) { // construct the fields directly
}
private:
string name;
int hp;
};
And your PokemonStation class, rewritten using a vector for the list of Pokemon:
class PokemonStation {
private:
vector<Pokemon> list;
public:
PokemonStation() {}
PokemonStation(int x):id(x) {}
int id;
void assignToList(Pokemon x)
{
list.push_back(x); // add x to the list
}
};
If you want to print a Pokemon with cout <<, then you'll have to overload the << operator to define what gets printed. Add this into your class:
class Pokemon {
public:
...
friend ostream& operator<<(ostream& out, const Pokemon& p) {
out << p.name; // just print the name
return out;
}
...
};
Just make sure that you're couting a Pokemon, not a pointer-to-Pokemon (Pokemon*), and you won't get an address.
I want float variable 'avg' to be returned and then in the main pass it to 'void batsman::display(float a)' using a parameter. then display the average marks in display method. this method gives me 2 errors. any other way?
#include<iostream.h>
class batsman
{
int marks[5];
char name[15],country[15];
public:
void input();
float cal();
void display();
};
void batsman::input()
{
int i;
cout<<"Enter player name: ";
cin>>name;
cout<<"Enter player country: ";
cin>>country;
cout<<"Enter player marks"<<"\n";
for(i=0;i<5;i++)
{
cout<<"Mark "<<i+1<<": ";
cin>>marks[i];
}
}
float batsman::cal()
{
int i;
int tot=0;
float avg;
for(i=0;i<5;i++)
{
tot=tot+marks[i];
}
avg=(float)tot/5;
return avg;
}
void batsman::display(float a)
{
float avg1;
avg1=a;
cout<<"Player name: "<<name<<"\n";
cout<<"Player country: "<<country<<"\n";
cout<<"Average: "<<avg1<<"\n";
}
int main()
{
batsman b1;
b1.input();
b1.cal();
b1.display(b1.batsman::cal());
//cout<<"Average: "<<b1.batsman::cal()<<"\n";
}
The code has several errors.
iostream.h should be iostream
using namespace std; // add this at top so that cout is found
display() should be display(float a) in the class declaration.
After those changes the code ran as expected.
Change display's definition in your class to display(float a), and prepend std:: to cout and cin. As a recommendation, don't use iostream.h, use iostream.
I'm new to c++ because all throughout our lab activities we just use C# and I'm still trying get the gist of it. So our last lab, which uses c++, is to show our genealogy-our family tree- and my problem right now is printing. Can someone point out what's wrong in my function or why it's not printing and what's the best way to do it?
#include <iostream>
#include <string>
using namespace std;
class parent
{
public:
void setMom(string mom)
{
mother=mom;
}
void setDad(string dad)
{
father=dad;
}
string getDad(void)
{
return father;
}
string getMom(void)
{
return mother;
}
protected:
string mother;
string father;
};
class Member: public parent
{
public:
string name;
Member()
{
}
void setName(string kid)
{
name=kid;
}
void setStatus(string stat)
{
status=stat;
}
void setAge(int num)
{
age=num;
}
string getName()
{
return name;
}
private:
string status;
int age;
};
char addPerson()
{
Member person;
char mom[50];
char dad[50];
char kid[50];
char stat[7];
int num;
cout<<"Name: ";
cin>>kid;
person.setName(kid);
cout<<"Age: ";
cin>>num;
person.setAge(num);
cout<<"Status(Living/Diseased): ";
cin>>stat;
person.setStatus(stat);
cout<<"Father: ";
cin>>dad;
person.setDad(dad);
cout<<"Mother: ";
cin>>mom;
person.setMom(mom);
}
my function for printing.
void showme()
{
Member person;
cout<<person.getMom();
}
//-----------------------------------------------------MAIN--------------------------------------------------
int main()
{
while(1)
{
int choice;
cout<<" 1. Add member"<<"\n";
cout<<" 2. Edit member"<<"\n";
cout<<" 3. Show family tree"<<"\n";
cout<<" 4. Exit"<<"\n";
cin>>choice;
if(choice==1)
{
addPerson();
}
else if(choice==2)
{
}
else if(choice==3)
{
showme();
}
else if(choice==4)
{
break;
}
}
}
I don't know how to call my class functions into printData(Testscore&) and readData(TestScore).
Also, could someone tell me why my Average() isn't being called to the main? I just learned about using static member variables and static member functions and was wondering if I am using them incorrectly.
The readData function:
Does not use copy constructor.
Reads all instance variables like the student's names and all their
grades.
Uses functions to store the variables, name, element of each grade of array pointed to private pquiz, and static member
grades of how many grades to read.
The printData function:
Writes the name and average grade of the quizzes.
Uses copy constructor.
This is my program so far:
#include <iostream>
#include <string>
using namespace std;
class TestScore {
private:
static int grades;
string name;
double *pquiz;
double average;
public:
TestScore();
~TestScore();
void setName(string);
static void setGrades(int);
void setPquiz(double *);
void setAverage(double);
string getName();
static int getGrades();
double getPquiz();
void readData(TestScore &);
void printData(TestScore);
double Average(double *, int);
static void Grade(int);
};
TestScore::TestScore() {
name="";
pquiz=new double[grades];
average=0;
}
void TestScore::setName(string name1) {
if(name1!="1") {
name=name1;
}
}
void TestScore::setPquiz(double *pquiz1) {
if(pquiz>=0) {
pquiz=pquiz1;
}
}
void TestScore::setGrades(int grades1) {
if(grades1>=0) {
grades=grades1;
}
}
void TestScore::setAverage(double average1) {
if(average1>=0) {
average=average1;
}
}
string TestScore::getName() {
return name;
}
int TestScore::getGrades() {
return grades;
}
double TestScore::getPquiz() {
return *pquiz;
}
double Average(double *pquiz, int grade) {
int count;
double total=0;
double average=0;
for(count=0; count<grade; count++) {
total+=pquiz[count];
}
average=total/grade;
return average;
}
void readData(TestScore&) {
}
void printData(TestScore) {
}
TestScore::~TestScore() {
delete [] pquiz;
pquiz=0;
}
int TestScore::grades=0;
void TestScore::Grade(int a) {
grades+=a;
}
int main() {
const int grades = 3;
const int students = 4;
TestScore exam;
string student;
int grade;
double *pquiz;
double average;
for(int i=0; i<students; i++) {
cout<<"Student "<<(i+1)<<": ";
cin>>student;
exam.setName(student);
cout<<endl;
for(int count=0; count<grades; count++) {
cout<<"Quiz "<<(count+1)<<": ";
cin>>pquiz[count];
exam.setPquiz(pquiz);
exam.getPquiz();
while(pquiz[count]<0) {
cout<<"Error, invalid test score, please try again."<<endl;
cout<<"Quiz "<<(count+1)<<": ";
cin>>pquiz[count];
}
}
exam.setAverage(average);
cout<<exam.getName()<<" average is "<<Average(pquiz, grade)<<endl<<endl;
}
readData(exam);
printData(exam);
return 0;
}
Don't use static anywhere, at least not for now. You have too many variables of the same name, scattered all over the place. Try to clean them up.
TestScore::TestScore()
{
name = "";
//pquiz = new double[grades];//#grades is undefined
pquiz = NULL;
average = 0;
}
grades is not defined yet, it could be zero, or it could be -817. You should just remove that line, or you can put something like pquiz = new double[10] that's if you are sure the number of quiz will not exceed 10.
TestScore::~TestScore()
{
if (pquiz) delete[] pquiz;
pquiz = NULL;
}
delete pquiz only if it is not NULL
int main() {
const int grades = 3;
const int students = 4;
TestScore exam;
string student;
int grade;
double *pquiz;
...
This is a different pquiz, it is a pointer which points to nothing, it doesn't really exist, you can't use it like that.