This question already has answers here:
string and int concatenation in C++ [duplicate]
(3 answers)
Closed 2 years ago.
Hello I am trying to make a game somewhat like Pokemon but I'm stuck on printing stats.
I am trying to output a level with it showing what level the animal reached.
Any help on the fact I'm not getting expected results?
My code:
visualanimal.h (not used yet):
#include <string>
#ifndef VISUALANIMAL_H
#define VISUALANIMAL_H
using namespace std;
using namespace Animals;
/*** Visual based on original class
#author Adam Petla
***/
class VisualAnimal : Animal {
public:
string imageFileURL;
int size;
VisualAnimal() {
this->imageFileURL = "";
this->size = 0;
}
};
#endif
animal.h :
#include <string>
#include <stdio.h>
#include <iostream>
#ifndef ANIMAL_H
#define ANIMAL_H
using namespace std;
namespace Animals {
class Animal {
public:
string name;
int minlevel;
int level;
int maxlevel;
int baseattack;
int baseattackraise;
int attack;
int basedefense;
int basedefenseraise;
int defense;
int basespeed;
int basesppedraise;
int speed;
int basespecial;
int basespecialraise;
int special;
char type;
Animal() {
name = "DOG";
minlevel = 0;
level = 1;
maxlevel = 100;
baseattack = 1;
baseattackraise = 1;
basedefense = 1;
basedefenseraise = 1;
basespecial = 1;
basespecialraise = 1;
basespeed = 1;
basesppedraise = 1;
};
private:
void printstats() {
//cout << "Attack : " << this->
};
void raiseattack() {
this->attack += this->baseattackraise;
}
void raisedefense() {
this->defense += this->basedefenseraise ;
}
void raisespeed() {
this->speed += this->basesppedraise;
}
void raisespecial() {
this->special += this->basespecialraise;
}
void raisestats() {
raiseattack();
raisedefense();
raisespeed();
raisespecial();
}
void updatestats(char type) {
switch (type) {
case 'l':
raisestats();
}
}
public :
void raiselevel() {
this->level++ ;
this->type = 'l';
updatestats(this->type);
string output = "Level Up!Your " + string(this->name) + string("has reached level");
cout << output;
cout << this->level + ".Its stats are now";
printstats();
};
};
}
#endif
animal.cpp :
// Animals.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
#include "animal.h"
#include "visualanimal.h"
using namespace std;
int main()
{
using namespace`` Animals;
Animal test;
test.raiselevel();
cout << "Hello World!\n";
return -1;
}
My expected results: DOG reached level 2.
My actual results DOG reached level
Anybody know an answer
It doesn't show any level in output anybody know why?
Change the following:
cout << this->level + ".Its stats are now";
To:
cout << this->level << ".Its stats are now";
You were getting incorrect output because you are trying to concatenate a string and an int.
The correct way to concatenate a string to an int is using std::to_string():
int val = 2;
std::string x = "hello";
std::string output = std::to_string(val) + x;
+ has a higher precedence than <<, so the line cout << this->level + ".Its stats are now"; is evaluated as cout << (this->level + ".Its stats are now"); - the value of level is used as an offset into a string literal ".Its stats are now", which is not what you want.
Change it to
cout << this->level << ".Its stats are now";
Or see here how to concatenate an int with a string.
Related
I am writing some C++ code to create an item of a class i have created inside a vector of another class. I seem to be able to create the items inside the vector but when i try to read a variable of the item inside the vector i get the error
Exception thrown: read access violation.
_Right_data was 0x8.
inside the document xstring.
I think it might have something to do with me not actually creating each team inside the vector.
the code i have written that is relavent is
for (int x = 1; x <= mainLeague.getNumTeams(); x++) {
std::cout << "please enter the name of team " << x << ":";
std::getline(std::cin, currLine);
parsed = parseText(currLine, &posResponsesTeamNames);
if (parsed == 2) {
prepForEnd();
return 1;
}
else if (parsed == 0) goto enterTeamNames;
mainLeague.createTeam(currLine);
}
std::cout << mainLeague.getName(5);
}
#pragma once
#include "team.h"
#include <string>
#include <vector>
#include <iostream>
class league
{
std::vector<team*> teams;
int numTeams, numInitTeams = 0;
const float sysCon = 0.5;
public:
league(int a);
int getNumTeams();
void initVector(int numTeams);
void createTeam(std::string name);
std::string getName(int num);
};
void league::createTeam(std::string name)
{
if (numInitTeams < teams.size()) {
team currTeam = team::team(name);
teams.at(numInitTeams) = &currTeam;
numInitTeams;
}
else {
std::cout << "error max amount of teams already created";
}
}
#pragma once
#include<string>
class team
{
float RD;
int rating;
std::string name;
public:
team(std::string name);
team();
std::string getName();
};
std::string team::getName()
{
return team::name;
}
I'm working on a multiple inheritance exercise and I'm running into a strange error. My code is not returning the correct information to the console. It is just outputting zero, I have checked multiple times in my code and I can't seem to find anything obviously wrong. I'm fairly new to C++ so any help I would appreciate it, in addition to any other critique.
The console will output
Maverick
South station
50 - passengers, is ok
40 - speed
0 - it is supposed to take distance/mph and output 2.6 in this case, but is returning nothing.
MBTA.cpp
#include "MBTA.h"
//objects
transportation Dest;
MBTA::MBTA()
{
}
MBTA::MBTA(string strIn, string strInTransport, int iIn, int distIn, int eIn)
{
setTrain(strIn);
//Destination
Dest.setTransport(strInTransport);
//set passengers
setPass(iIn);
Dest.setMilesToDest(distIn);
engine.setMPH(eIn);
//outputs train information
printTrainDestinationHours();
//used printf as I was running into issue with using cout here
//cout << " I am going to ";
printf("I am going to %s\n", Dest.getTransport().c_str());
//uses engine stats function
cout << "I go " << engine.getMPH() << endl;
printf("It will take me %.2f hours to arrive", redline.getTotal());
}
void MBTA::setTravelDist(int iIn)
{
double destdistance = Dest.getDist();
double trainMPH = engine.getMPH();
//this divides miles by MPH, this might return a float
redline.setTotal(50, 10);
}
MBTA::~MBTA()
{
}
MBTA.H
#pragma once
#include "train.h"
class MBTA :
public train
{
public:
engine engine;
train redline;
MBTA();
//train, destination, passengers, traveldist, speed
MBTA(string, string, int, int, int);
void setTravelDist(int);
//double getTotal();
//uses engine stats function
//double total = 0;
~MBTA();
};
Train.cpp
#include "train.h"
#include <iostream>
#include <cstdio>
#include <cmath>
using std::string;
using std::cout;
using std::endl;
//object member for transport
transportation tTrain;
train::train()
{
}
void train::printTrainDestinationHours()
{
printf("\n\nTrain type: %s\n", getTrain().c_str());
//passengers
printf("I have %d passengers\n", getPass());
}
void train::setPass(int iIn)
{
passengers = iIn;
}
int train::getPass()
{
return passengers;
}
void train::setTrain(string strIn)
{
trainName = strIn;
}
string train::getTrain()
{
return trainName;
}
void train::setTotal(int aIn, int bIn)
{
//dist / mph
total = aIn / bIn;
}
double train::getTotal()
{
return total;
}
train::~train()
{
}
Train Header
#pragma once
#include <iostream>
#include <cstdio>
using std::string;
using std::cout;
using std::endl;
#include "engine.h"
#include "transportation.h"
class train : public transportation
{
public:
train();
void printTrainDestinationHours();
//set and get destination
//num of pass
void setPass(int);
int getPass();
//train
void setTrain(string);
string getTrain();
//distance
void setTotal(int, int);
double getTotal();
~train();
private:
engine engineStats;
int total = 0;
string trainName = "";
string destination = "";
int passengers = 0;
};
engine.cpp
#include "engine.h"
engine::engine()
{
}
void engine::setMPH(int iIn)
{
MPH = iIn;
}
int engine::getMPH()
{
return MPH;
}
engine::~engine()
{
}
engine header
#pragma once
class engine
{
public:
engine();
//return
void setMPH(int);
int getMPH();
~engine();
protected:
int MPH = 0;
};
'''
transportation cpp
'''
#pragma once
class engine
{
public:
engine();
//return
void setMPH(int);
int getMPH();
~engine();
protected:
int MPH = 0;
};
transportation header
#include "transportation.h"
transportation::transportation()
{
}
void transportation::setTransport(string strIn)
{
destination = strIn;
}
string transportation::getTransport()
{
return destination;
}
void transportation::setMilesToDest(int iIn)
{
MilesToDestination = iIn;
}
int transportation::getDist()
{
return MilesToDestination;
}
transportation::~transportation()
{
}
main file
#include <iostream>
using std::string;
using std::cout;
using std::endl;
using std::cin; //for ignore
#include "challenger.h"
#include "MBTA.h"
#include "plane.h"
int main()
{
//object composition of vehicle type
// vehicle type location, passengers, MPH , distance
challenger SRT8707("Boston", 2, 100, 200);
plane boeing("boeing", "houston", 50, 500, 300);
MBTA redline("Maverick", "South station", 50, 100, 40);
//pause and blank line
cout << endl << endl;
cin.ignore();
}
I got some problem when run my coding. I got 2 separate file to create RetailItem class and create main. I create both in project.
Below are main.cpp
//main
#include "retailitem.h"
#include <iostream>
#include <iomanip>
using namespace std;
using std::cout;
void displayItem(RetailItem *, const int);
int main()
{
const int Item = 3;
RetailItem ritem[Item] ={ { "Jacket", 12, 59.95 },
{ "Designer Jeans", 40, 34.95 },
{ "Shirt", 20, 24.95 } };
//cout << fixed << setprecision(2);
void displayItem(RetailItem *ritem, const int Item){
cout <<" DESCRIPTION UNITS ON HAND PRICE";
cout<<"=================================================================\n";
for (int i = 0; i < Item; i++)
{
cout << setw(12) << ritem[i].getDesc();
cout << setw(12) << ritem[i].getUnits();
cout << setw(8) << ritem[i].getPrice();
}
cout << "===================================================================";
}
return 0;
}
and there one more file retailitem.h
//RetailItem class
#include <string>
using namespace std;
class RetailItem
{
private:
string description;
int unitsOnHand;
double price;
public:
RetailItem(string,int,double);
void setDesc(string d);
void setUnits(int u);
void setPrice(double p);
string getDesc();
int getUnits();
double getPrice();
};
RetailItem::RetailItem(string desc, int units, double cost)
{
description = desc;
unitsOnHand = units;
price = cost;
}
void RetailItem::setDesc(string d)
{
description = d;
}
void RetailItem::setUnits(int u)
{
unitsOnHand = u;
}
void RetailItem::setPrice(double p)
{
price = p;
}
string RetailItem::getDesc()
{
return description;
}
int RetailItem::getUnits()
{
return unitsOnHand;
}
double RetailItem::getPrice()
{
return price;
}
when compile and run main,
[Error] a function-definition is not allowed here before '{' token
[Error] expected '}' at end of input
I don't know what to fix, how can I solve it?
The error message undoubtedly contained a line number that told you where the problem was. That's an important part of describing the problem. But here it happens to be obvious: void displayItem(RetailItem *ritem, const int Item){ is the start of a function definition. You can't define a function inside another function. Move this outside of main.
I have this class
#include "Room.h"
#include "Book.h"
#include <cstdlib>
#include <iostream>
static int book_counter = 100;
//Constructors
Book::Book() {
for(int i = 0; i < 13; i++) {
this->customer_name += 97 + rand() % 26;
}
this->arrival = rand() % 30;
this->duration = 1 + (rand() % 10);
this->ppl = 1 + rand() % 5;
this->room = nullptr;
this->book_code = book_counter++;
}
Book::Book(std::string nm, int arr, int dur, int ppl) {
this->customer_name = nm;
this->arrival = arr;
this->duration = dur;
this->ppl = ppl;
this->room = nullptr;
this->book_code = book_counter++;
}
//Methods
int Book::getArr() {
return arrival;
}
int Book::getDur() {
return duration;
}
int Book::getPpl() {
return ppl;
}
void Book::anathesi(Room* x) {
this->room = x;
}
int Book::getBookCode() {
return book_code;
}
Room* Book::getRoom() {
return room;
}
std::string Book::getCustomerName() {
return customer_name;
}
which includes a string getter method getCustomerName().
When I call this method on main, via an instance created via the first constructor, everything works fine. On the other hand, if the instance is created via the second constructor, the method will cause a segmentation fault.
It seems like customer_name has an infinite length, thus causing a segmentation fault when I try to return it.
The method is called in main with this line of code:
cout << hotel.getBooks(i)->getBookCode() << " " << hotel.getBooks(i)->getCustomerName()
<< " " << hotel.getBooks(i)->getRoom()->getRoomCode() << "\n";
I am new into C++, so please elaborate my fault as much as needed.
The header file for class Book:
#ifndef PROJECT_BOOK_H
#define PROJECT_BOOK_H
#include <string>
class Room;
class Book {
protected:
std::string customer_name;
int book_code;
int arrival;
int duration;
int ppl;
Room* room;
public:
Book();
Book(std::string nm, int arr, int dur, int ppl);
void anathesi(Room* x);
int getArr();
int getDur();
int getPpl();
int getBookCode();
std::string getCustomerName();
Room* getRoom();
};
#endif //PROJECT_BOOK_H
In Hotel.h:
private: std::vector<Book*> books;
public: Book* getBooks(int i);
In Hotel.cpp:
Book* Hotel::getBooks(int i) {
return books[i];
}
Found the problem and fixed it.
I was creating instances with this piece of code:
Book obj(onoma, afiksh - 1, meres, arithmos);
which caused the segmentation I said.
I changed this to:
Book *obj = new Book(onoma, afiksh - 1, meres, arithmos);
and fixed the problem. Thanks for your time and help.
Unfortunately, I don't really know why this works, but it does, everything functions properly. Therefore I guess I'll have to look at new documentation.
I'm trying to do an insertion sort on a vector of baseball pitchers I created yesterday with help from a previous post. I want to sort the pitchers in ascending order by ERA1. I have gotten the insertion sort to work in the past for a set of integers. I think I have a syntax error in my code for the insertion sort. Up until trying to add the insertion sort this program was working well. I get an error - expected unqualified id before [ token. Thanks in advance for any help.
#ifndef Pitcher_H
#define Pitcher_H
#include <string>
#include <vector>
using namespace std;
class Pitcher
{
private:
string _name;
double _ERA1;
double _ERA2;
public:
Pitcher();
Pitcher(string, double, double);
vector<Pitcher> Pitchers;
string GetName();
double GetERA1();
double GetERA2();
void InsertionSort(vector<Pitcher>&);
~Pitcher();
};
#endif
#include "Pitcher.h"
#include <iostream>
#include <string>
#include <vector>
#include <iomanip>
using namespace std;
Pitcher::Pitcher()
{
}
Pitcher::~Pitcher()
{
}
string Pitcher::GetName()
{
return _name;
}
Pitcher::Pitcher(string name, double ERA1, double ERA2)
{
_name = name;
_ERA1 = ERA1;
_ERA2 = ERA2;
}
double Pitcher::GetERA1()
{
return _ERA1;
}
double Pitcher::GetERA2()
{
return _ERA2;
}
#include "Pitcher.h"
#include <iostream>
#include <string>
#include <vector>
#include <iomanip>
void InsertionSort(vector<Pitcher> Pitchers&);
using namespace std;
int main()
{
vector<Pitcher> Pitchers;
cout << "Pitcher" << setw(19) << "Item ERA1" << setw(13) <<
"Item ERA2\n" << endl;
Pitcher h2("Bob Jones", 1.32, 3.49);
Pitchers.push_back(h2);
Pitcher h3("F Mason", 7.34, 2.07);
Pitchers.push_back(h3);
Pitcher h1("RA Dice", 0.98, 6.44);
Pitchers.push_back(h1);
for(unsigned i = 0; i < Pitchers.size(); ++i)
{
cout << setw(19);
cout << left << Pitchers[i].GetName() << "$" <<
setw(10) << Pitchers[i].GetERA1() <<
right << "$" << Pitchers[i].GetERA2() << "\n";
}
cout << endl;
//------------------------------------------------------
InsertionSort(Pitchers);
//Now print the numbers
cout<<"The numbers in the vector after the sort are:"<<endl;
for(int i = 0; i < Pitchers.size(); i++)
{
cout<<Pitchers[i].GetERA1()<<" ";
}
cout<<endl<<endl;
system("PAUSE");
return 0;
}
void InsertionSort(vector<Pitcher> &Pitchers)
{
int firstOutOfOrder = 0;
int location = 0;
int temp;
int totalComparisons = 0; //debug purposes
for(firstOutOfOrder = 1; firstOutOfOrder < Pitchers.size() ; firstOutOfOrder++)
{
if(Pitcher.GetERA1([firstOutOfOrder]) < Pitcher.GetERA1[firstOutOfOrder - 1])
{
temp = Pitcher[firstOutOfOrder];
location = firstOutOfOrder;
do
{
totalComparisons++;
Pitcher.GetERA1[location] = Pitcher.GetERA1[location - 1];
location--;
}while(location > 0 && Pitcher.GetERA1[location - 1] > temp);
Pitcher.GetERA1[location] = temp;
}
}
cout<<endl<<endl<<"Comparisons: "<<totalComparisons<<endl<<endl;
}
Here:
for(firstOutOfOrder = 1; firstOutOfOrder < Pitchers.size() ; firstOutOfOrder++)
{
if(Pitchers[firstOutOfOrder].GetERA1() < Pitchers[firstOutOfOrder-1].GetERA1())
{ //^^^your way was not right, should first access the object then
//access member function
temp = Pitcher[firstOutOfOrder];
//^^^should be Pitchers, similar errors below
location = firstOutOfOrder;
do
{
totalComparisons++;
Pitcher.GetERA1[location] = Pitcher.GetERA1[location - 1];
//^^^similar error as inside if condition
location--;
}while(location > 0 && Pitcher.GetERA1[location - 1] > temp);
//^^^similar error as inside if condition
Pitcher.GetERA1[location] = temp;
//^^similar error as in if condition and name error
}
}
Meanwhile, you put the InsertionSort declaration as a member of the Pitcher class
public:
.
.
void InsertionSort(vector<Pitcher>&);
and you also declare the same function inside main,
void InsertionSort(vector<Pitcher> Pitchers&);
//should be vector<Pitcher>& Pitchers
using namespace std;
int main()
the member function probably should be removed in your case. InsertionSort is not a responsibility of your Pitcher class.
Unless this is homework, you're better off using the build in sort from
<algorithm>