So, I'm making a text game. It opens and works fine then will abruptly close with no apparent trigger and open a new instance of itself. After it does this once it does not do it again. If I'm doing other things stupidly I would also like to know this. Heads up that this is a lot of code because I do not know where the problem lies. I tried to cut out the non important bits though. Would also like to know how to read write files in another directory that isn't the root one the exe is in. I am using Code::Blocks to compile. If the header files are important I can include them.
//#libraries
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <string>
#include "windows.h"
#include "math.h"
#include "time.h"
#include "Dungeon.h"
using namespace std;
//functions
int roomLogic();
void stats();
void options();
void devConsole();
void tutorial();
//Choose Class functions
void chooseClass();
void choosePaladin();
void chooseWarlock();
void chooseRanger();
void chooseWarrior();
void chooseRogue();
//global variables
int textSpeed;
int turns = 0;
bool debug = false;
//Player Stats
//Name and Such
int kills = 0;
int killScore = 0;
int damageDelt = 0;
int damageTaken = 0;
int score = 0;
string name;
string Class;
string race;
//Items
int keys = 0;
int money = 10;
int moneySpent = 0;
//Combat
int att = 10;
int def = 10;
int speed = 10;
int sneak = 10;
int eva = 10;
int perc = 10;
int accuracy = 10;
int health = 100;
int maxHealth = 150;
int mp = 50;
int magicPower = 10;
int main()
{
cout << "WHOLE BUNCH OF INTRO TEXT THAT YOU DO NOT NEED TO READ BECAUSE
THERE IS A LOT" << endl;
Sleep(1000);
//Text Speed Definition
cout << "How do you like your text speed? 'Slow', or 'Fast'?" << endl;
cout << "Type your answer and press ENTER to send" << endl;
string textSpeedInput;
cin >> textSpeedInput;
bool success = false;
//a while statement to get them to say yes no and set a text speed, not
important
cout << "If you have never played the game before and would like a
tutorial, type \n'tutorial' if not type 'no'" << endl;
string tutor;
cin >> tutor;
bool tut = false;
//another while statement thing that I cut out the function literally just
couts
chooseClass();
stats();
roomLogic();
system("PAUSE");
exit(0);
return 0;
}
void chooseClass()
{
cout << "Choice is fun, but randomness can be too, Would you like to
choose your class and race(Yes) or get a random class and race(No)" <<
endl;
string willChoose;
cin >> willChoose;
if(willChoose == "Yes" || willChoose == "yes")
{
cout << "Would you like to be a:\n" << endl;
cout << "Paladin (+3 Defense, -1 Speed)," << endl;
cout << "Warlock (+3 Magic Power, -1 Defense)," << endl;
cout << "Ranger (+2 Accuracy, +1 Perception, +1 Speed, -2 Defense)," <<
endl;
cout << "Warrior (+2 Attack, +1 Defense, -1 Magic Power), or" << endl;
cout << "Rogue (+2 Stealth, +1 Attack, +1 Evasion, +1 Speed, -3
Defense)?" << endl;
bool hasChoosen = false;
cin >> willChoose;
//another cut out while statement
code has broken by this point. I have no clue why. Please help is it an augment I need in my int main or something?
Here is an example read write I use just so you know:
ifstream x_file (".filenamehere.txt"); x_file >> variable to change;
x_file.close();
And to write:
ofstream y_file (".filename.txt"); y_file << thing to write; y_file.close();
Related
i am a beginner in programming in C++. In my class we were recently showed to use functions and parameters. We were left an assignment where we are supposed to work with functions, except the only problem is i can't seem to get a start. I have wrote two functions so far. My main function, which asks for input from the user. Also another function which uses this input to create a new integer i will later need. I'm sure there are several mistakes in my code, but right now i really only need to know why only my main function will execute. I have been looking for hours, and switching stuff around, just to get another function other than the main to run, but my it will only run the main function and then the program will end. After inputting data from the user, the program will end. I haven't been able to get any other function to run other than the main, since i started this assignment. I am using visual studio 2017. Sorry for the trouble.
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int digits(int zip);
int main() {
int zip = 0;
cout << "Enter zipcode: ";
cin >> zip;
return 0;
}
int digits(int zip){
int d5 = int();
d5 = zip % 10;
cout << "test: " << d5 << endl;
return d5;
}
You need to call the function digits
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int digits(int zip);
int main() {
int zip = 0;
cout << "Enter zipcode: ";
cin >> zip;
int data = digits(zip);
cout<<"test: "<<data<<endl;
return 0;
}
int digits(int zip){
int d5 = int();
d5 = zip % 10;
// cout << "test: " << d5 << endl;
return d5;
}
C++ looks for the main function and executes whatever is in it. In your case, it creates a new variable 'zip', asks the user for input, then inserts that value into the zip variable. Then it returns 0 and stops running.
You must call the function digits() inside int main(). Like so:
int main() {
int zip = 0;
cout << "Enter zipcode: ";
cin >> zip;
digits(zip);
return 0;
}
int digits(int zip){
int d5 = int();
d5 = zip % 10;
cout << "test: " << d5 << endl;
return d5;
}
Additionally, be aware that after executing the digits() function this program will simply return 0, not manipulating the 'd5' variable (returned by int digits()) in any way.
Also, it is not a good idea to cout anything inside additional functions. This makes it difficult to reuse the function. To keep the function as versatile as possible, make sure it only performs one task. In your case it should look something like this:
int main() {
int zip = 0;
cout << "Enter zipcode: ";
cin >> zip;
cout << "test: " << digits(zip) << endl;
return 0;
}
int digits(int zip){
int d5 = int();
d5 = zip % 10;
return d5;
}
You need to call the function digits before hand otherwise the program will skip over the function entirely so the above code should actually look something like this:
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int digits(int zip);
int main() {
int zip = 0;
cout << "Enter zipcode: ";
cin >> zip;
return 0;
}
int digits(int zip){
int d5 = int();
d5 = zip % 10;
cout << "test: " << d5 << endl;
return d5;
}
Also on a side note in d5 = zip % 10; if your looking for it to be more accurate just define d5 as a double or a float.
I have the following files:
main.cpp
shop.hpp
player.hpp
With the following code in each of them:
main.ccp:
#include <iostream>
#include <cstdlib>
#include "shop.hpp"
using namespace std;
string *inventory= new string[3];
int invGold= 355;
int main(void){
shop store;
store.store();
}
shop.hpp:
#include <iostream>
#include <cstdlib>
using namespace std;
class shop{
public:
string shopOption;
string shopOptions[6]= {"Buy", "buy", "Sell", "sell", "Leave", "leave"};
string shopInv[3]= {"Sword", "Potion", "Arrows x 25"};
int shopInvAmount= sizeof(shopInv)/sizeof(shopInv[0]);
int shopPrices[3]= {250, 55, 70};
shop(){
cout << "Shopkeeper: We buy, we sell, what's your buisness?" << endl;
}
void store(void){
getline(cin,shopOption);
if(shopOption.compare(shopOptions[0]) == 0 || shopOption.compare(shopOptions[1]) == 0){
buy();
}
else if(shopOption.compare(shopOptions[2]) == 0 || shopOption.compare(shopOptions[3]) == 0){
sell();
}
else if(shopOption.compare(shopOptions[4]) == 0 || shopOption.compare(shopOptions[5]) == 0){
leave();
}
}
void buy(){
srand(time(0));
string buyQuotes[3]= {"What are you buyin', hon?", "Make it quick, I ain't got all day.", "Another day, another sell."};
int quotePick= rand() % sizeof(buyQuotes)/sizeof(buyQuotes[0]) - 1;
if (quotePick < 0){
quotePick= 0;
}
else if (quotePick > (sizeof(buyQuotes)/sizeof(buyQuotes))){
quotePick= sizeof(buyQuotes)/sizeof(buyQuotes);
}
cout << "TEST:" << sizeof(shopInv)/sizeof(shopInv[0]) << endl;
cout << buyQuotes[quotePick] << endl;
cout << "SHOP INVENTORY" << endl << "--------------" << endl;
cout << endl;
for (int i=0; i < sizeof(shopInv)/sizeof(shopInv[0]); i++){
cout << shopInv[i]<< ": " << shopPrices[i] << endl;
}
cout << endl << "What'll it be?:";
getline(cin,shopOption);
}
void sell(){
}
void leave(){
}
};
and player.hpp
class player{
public:
int playerHP= 18;
string playerInv[5] {};
int playerGold= 355;
};
Now, what i'd like to do, is that after the character selects the items they want to buy, and te amount of it, (Not programmed yet) check the price of the combined items, and see if the character has enough money on hand, and if the character buys the items, add them to the player's inventory.
But i'd like to keep the values the store uses, and everything related to the player in different class files.
Thing is, I have no idea how to pull something like that.
So, is t possible to access a class' variable from another class that is in another file althogether?
And if isn't, how would you suggest i get around this problem?
Start reading here: How does the compilation/linking process work? to get multiple files working for you. Odds are pretty good that whatever coding environment you are using will automate the process for you.
Then consider making an item class
class Item
{
public:
Item(string name, int price): mName(name), mPrice(price)
{
}
string getName()
{
return mName;
}
string getPrice()
{
return mPrice;
}
// other functions
private:
string mName;
int mPrice;
// other stuff
}
In Shop and Player, keep a list of Items
vector<Item> items;
When a Player tries to buy an item, find it in the list, ensure the Player can afford it, remove it from the Shop's list and add it to the Player's list.
I have tried to complete a C++ exercise where you have to complete function definitions for a 'Golf' function and devise a program based on this however, I am having a problem with one of the functions.
Part of the goal of the function, wants you to return 1 if the user has entered a name for the golf player, and return 0 if no name is entered.
I am experiencing some difficulty with this, as when I run the program, I am always getting 1 returned to the main.
Underneath I have listed what I have done so far for each file:
golf.h
#ifndef GOLF_H
#define GOLF_H
const int Len = 40;
struct golf {
char fullname[Len];
int handicap;
};
void setgolf(golf &g, const char *name, int hc);
int setgolf(golf &g);
void handicap(golf &g, int hc);
void showgolf(const golf &g);
#endif /* GOLF_H */
golf.cpp
#include "golf.h"
#include "iostream"
void setgolf(golf &g, const char *name, int hc) {
strcpy(g.fullname, name);
g.handicap = hc;
}
int setgolf(golf &g) {
std::cout << "Golfer's name:";
std::cin.getline(g.fullname, Len);
if (std::cin.get() == '\0')
return 0;
std::cout << "Golfer's handicap: ";
std::cin >> g.handicap;
return 1;
}
void handicap(golf &g, int hc) {
g.handicap = hc;
std::cout << g.fullname << "'s new handicap is:" << g.handicap;
}
void showgolf(const golf &g) {
std::cout << "Player's Name:" << g.fullname << std::endl;
std::cout << "Player's handicapped:" << g.handicap << std::endl;
}
main.cpp
#include <cstdlib>
#include <iostream>
#include "golf.h"
using namespace std;
int main(int argc, char** argv) {
int retuVal = 0;
golf ann;
setgolf(ann, "Ann Birdfree", 24);
showgolf(ann);
cout << "\n";
golf peter;
retuVal = setgolf(peter);
cout<<"return value is:"<<retuVal<<endl;
cout << "\nGolf details reset in new handicap\n";
handicap(peter, 5);
cout << "\nDetails reprinted";
showgolf(peter);
return 0;
}
Please let me know, what it is that I have done wrong, so that I can return 0 instead of returning 1 all of the time.
Thanks Jis.
In the function setgolf remove the following code:
if (std::cin.get() == '\0')
return 0;
and instead write...
if(strlen(g.fullname)==0)
return 0;
This is because when the user doesn't want to enter a name he just hits the enter key. This makes the string empty, since getline fills the character array until it is completely filled or it sees a newline character in the stream. So, if we just check its length, whether its greater than 0, then its enough. for furthur reference about getline see here
The probability of cin.get() returning '\0' is almost 0.
(If cin is connected to a terminal, it can only happen if the
user enters a control-#.) Maybe you want to return 0 if the user
enters an empty string?
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
//Long story short, trying to do a media library, but I am at a 100% Complete loss on why I cannot get this data to work. This is my Main.cpp
#include "CDclass.h"
bool fills = true;//Public Switch to turn on/off autofill of "Data" classes.
bool runner = true;//Public switch that helps with the program functionality(DO NOT EDIT)
void main()
{
int decision;
unsigned int total = 5;
vector<string> titles;
vector<double> time;
string artist;
string name;
titles.resize(total);
time.resize(total);
vector<cdStorage> Data;//A vector of classes
cdStorage newCD;
Data.push_back(newCD);
Data.push_back(newCD);
Data.push_back(newCD);//This was used as a sizing test and it works.
cdStorage::cdStorage(total);
//I used this to loop without restarting main.
while(runner == true)
{
if(fills == true)//Autofill to get the program running
{
artist = "Bunny";
name = "Bread";
for(unsigned int x = 0; x < Data.size(); x++)
{
cdStorage::cdStorage(total);
Data[x].setNewArtist(artist);
Data[x].setNewName(name);
for(unsigned int y = 0; y < total; y++)
{
titles[y] = "TestfieldBanana!";
time[y] = 12.13;
Data[x].setNewTitles(y, titles[y]);
Data[x].setNewTime(y, time[y]);
}
}
fills = false;
}
cout << Data[0].getNewArtist() << endl;
cout << "*******************" << endl <<
"*Media Awesomsauce*" << endl <<
"*******************" << "\n\n" <<
"********************" << endl <<
"* 1: Check Library *" << endl <<
"* 2: Add CD *" << endl <<
"* 3: Delete CD *" << endl <<
"* 4: Exit Program *" << endl <<
"********************" << "\n\n" <<
"Decision:_";
cin >> decision;
//The majority of all of this is very self explanatory.
if(decision == 1)
{
for(unsigned int x = 0; x < Data.size(); x++)
{
cdStorage::cdStorage(total);
cout << Data[x].getNewName() << "\t";
cout << Data[x].getNewArtist() << "\t";
for(unsigned int y = 0; y < total; y++)
{
//int length = Data[x].getNewName().length();
cout << "\t\t\t" << Data[x].getNewTitles(y);
cout << "\t" << Data[x].getNewTime(y) << endl;
}
}
}else if(decision == 2)
{
Data.push_back(newCD);
system("CLS");
cout << "What is the name of the CD: ";
cin >> name;
cout << "\nWhat is the name of the Artist: ";
cin >> artist;
cout << "\nHow many songs are there: ";
cin >> total;
cdStorage::cdStorage(total);
titles.resize(total);
time.resize(total);
Data[Data.size()].setNewName(name);
Data[Data.size()].setNewArtist(artist);
cout << "What are the song titles and lengths:\n";
for(unsigned int x = 0; x < total; x++)
{
cout << "Title " << x+1 << ": ";
getline (cin, titles[x]);
cout << "Length(Example: 3.36 for 3 mins and 36 seconds): ";
cin >> time[x];
cout << endl;
Data[Data.size()].setNewTitles(x, titles[x]);
Data[Data.size()].setNewTime(x, time[x]);
}
}else if(decision == 3)
{
}else if(decision == 4)
{
runner = false;
}else
{
system("CLS");
cout << "Error: You must choose a number between 1-5...\n\n";
system("pause");
system("CLS");
}
}
}
//This is my CDWorks.cpp
#include "CDclass.h"
//Constructor
cdStorage::cdStorage(){};
//Overloaded Constructor
cdStorage::cdStorage(unsigned int theTotal)
{
newTotal = theTotal;
newTitles.resize(newTotal);
newTime.resize(newTotal);
}
//Accessors
unsigned int cdStorage::getNewTotal() const
{
return newTotal;
}
string cdStorage::getNewTitles(unsigned int x) const
{
return newTitles[x];
}
double cdStorage::getNewTime(unsigned int x) const
{
return newTime[x];
}
string cdStorage::getNewArtist() const
{
return newArtist;
}
string cdStorage::getNewName() const
{
return newName;
}
//Mutators
void cdStorage::setNewTotal(unsigned int theTotal)
{
newTotal = theTotal;
}
void cdStorage::setNewTitles(unsigned int x, string theTitle)
{
newTitles[x] = theTitle;
}
void cdStorage::setNewTime(unsigned int x, double theTime)
{
newTime[x] = theTime;
}
void cdStorage::setNewArtist(string theArtist)
{
newArtist = theArtist;
}
void cdStorage::setNewName(string theName)
{
newName = theName;
}
//Destructor
cdStorage::~cdStorage(){}
//This is my CDClass.h
#include <iostream>
#include <string>
#include <vector>
using namespace std;
#ifndef CDCLASS_H
#define CDCLASS_H
class cdStorage
{
private:
unsigned int newTotal;
vector<string> newTitles;
vector<double> newTime;
string newArtist;
string newName;
public:
//Constructor
cdStorage();
//Overloaded Constructor
cdStorage(unsigned int);
//Destructor
~cdStorage();
//Accessors
unsigned int getNewTotal() const;
string getNewTitles(unsigned int) const;//The integer is to track which element needs returned.
double getNewTime(unsigned int) const;
string getNewArtist() const;
string getNewName() const;
//Mutators
void setNewTotal(unsigned int);
void setNewTitles(unsigned int, string);
void setNewTime(unsigned int, double);
void setNewArtist(string);
void setNewName(string);
};
#endif
Data[Data.size()] is accessing outside the vector Data, which is undefined behaviour, so anything can happen.
Also, I don't know what you think repeatedly calling cdStorage::cdStorage(total); does, but it doesn't do anything except create a new (anonymous) object that is immediately thrown away.
All the cdStorages you have created were created using the default (parameterless) constructor, which leaves newTotal totally uninitialized, and the vectors are both empty. You can't modify them by calling a constructor afterwards (I suspect that is what yo're trying to accomplish).
Since the vectors are empty, when you say e.g. newTitles[x] = theTitle;, you're accessing invalid memory, which means that your program, again, has undefined behaviour.
It's very difficult to say whether these are the cause of your problems, but you should probably fix them first before you go on.
You should probably review the chapter on constructors and instance creation in your Fine Book.
Data[Data.size()].setNewName(name);
This accesses past the end of the vector, it only has Data.size() elements, starting from zero. This is undefined behaviour and probably causing the problem.
It may not be the problem, but as you haven't said where the error happens it's hard to know. You have the failing program, you should be able to debug it and say where it blows up ... you've had three days to learn to use a debugger!
Until you know what you're doing I suggest you stop using [x] to access vectors and switch to using the at(x) function, which does the same thing but checks that x is a valid index and not larger than the vector's size. If you'd done that then you'd have got an exception at the first problem, instead of undefined behaviour and a stack overflow.
There are a number of other issues...
Put your include guards at the top of the file, not after other headers.
Never put using namespace at namespace scope in a header.
You keep doing this:
cdStorage::cdStorage(total);
What's that supposed to do and why do you keep doing it?
You should use member initializers in constructors instead of altering them in the constructor body:
cdStorage::cdStorage(unsigned int theTotal)
{
newTotal = theTotal;
newTitles.resize(newTotal);
newTime.resize(newTotal);
}
i.e. do this instead:
cdStorage::cdStorage(unsigned int theTotal)
: newTotal(theTotal), newTitles(theTotal), newTime(theTotal)
{ }
I am making a hot potato game that deals with inheritance. I have a potato class, player class and umpire class.
In calling the toss function within my umpire class I KEEP getting this same error and I can't seem to figure out why: terminate called throwing an exceptionAbort trap: 6
I went through and found that within umpire::start(), the call to Players.at(randU)->toss(*m) in my for loop is making this error come up. But everything looks fine to me.
Can anyone help me out? Thanks!
Umpire.cc
#include <iostream>
#include <string>
#include "potato.h"
#include "player.h"
#include "umpire.h"
#include "PRNG.h"
using namespace std;
// Declare globally
int gamecount=1;
// GLOBAL VARIABLES
bool first=false; // False if set has not started
PRNG rplayer;
// UMPIRE CONSTRUCTOR-------------------------------------------------------------------
Umpire::Umpire( Player::PlayerList &players ){
Players=players;
cout<<"\tMashed POTATO will go off after ";
cout.flush();
m=new Mashed(Players.size()-1);
cout << " tosses" << endl;
cout.flush();
cout <<"\tFried POTATO will go off after 5 tosses" << endl;
cout.flush();
f=new Fried(5);}
// UMPIRE DESTRUCTOR-------------------------------------------------------------------
Umpire::~Umpire(){
delete m;
delete f;}
// UMPIRE START------------------------------------------------------------------------
void Umpire::start(){
int randU;
int gameCount=1; // Keeps track of sets
// Check if you are at the end of the list.
if(Players.size()==1){
// Who won?
cout << Players.at(0)->getId() << "wins the Match!" << endl;
cout.flush();}
else{
// Print output for sets----------------------------------------------------------------
// See which potato is being used in the set
if(gameCount%2!=0){
cout << "Set " << gameCount << "-\tUser (mashed) [";
cout.flush();}
else{
cout << "Set " << gameCount << "-\tUser (fried) [";
cout.flush();}
gameCount++; // increase gamecount
// Outputting players left in the set
for(unsigned int i=0;i<Players.size();i++){
cout<<Players.at(i)->getId();}
cout <<"]: ";
cout.flush();
//Start Tossing--------------------------------------------------------------------------
randU=rplayer(Players.size()-1);
// Output A(id) or R(id)
if (randU%2==0){
cout<<"A("<<randU<<"), ";
cout.flush();}
else{
cout<<"R("<<randU<<"), ";
cout.flush();}
if(first==false){
for(unsigned int i=0; i<Players.size(); i++){
if(Players.at(i)->getId()==Players.at(randU)->toss(*m)){
Players.erase(Players.begin()+i);
cout << "Eliminated: "<< i << endl;
cout.flush();}
}
first=true;
f->reset();
start();
}
else{
for(unsigned int i=0; i<Players.size(); i++){
if(Players.at(i)->getId()==Players.at(randU)->toss(*f)){
Players.erase(Players.begin()+i);
cout << "Eliminated: "<< i << endl;
cout.flush();}
}
first=false;
m->reset();
start();
}
}
}
Player.cc
#include <iostream>
#include "player.h"
#include "potato.h"
#include "PRNG.h"
using namespace std;
// GLOBAL DECLARATIONS--------------------------------------------------------------------
PRNG randP;
// PLAYER CONSTRUCTOR---------------------------------------------------------------------
Player::Player(unsigned int id, Player::PlayerList &players){
pid=id;
Players=players;
lrpFLAG=false;}
// getId() returns the player's id--------------------------------------------------------
unsigned int Player::getId(){
return pid;}
// RNPlayer Constructor-------------------------------------------------------------------
RNPlayer::RNPlayer( unsigned int id, Player::PlayerList &players ) : Player(id,players){}
// TOSS FUNCTION--------------------------------------------------------------------------
unsigned int RNPlayer::toss( Potato &potato ){
unsigned int randnum;
if(potato.countdown()){ return getId(); }
for(;;){
randnum=randP(Players.size()-1);
if (randnum%2==0){
cout<<"A("<<randnum<<"), ";
cout.flush();}
else{
cout<<"R("<<randnum<<"), ";
cout.flush();}
// If our randomly selected player is not the current player...
if(Players.at(randnum)->getId()!=getId()){
break;}
}
return Players.at(randnum)->toss(potato);
}
// LRPlayer Constructor-------------------------------------------------------------------
LRPlayer::LRPlayer( unsigned int id, Player::PlayerList &players ) : Player(id,players){}
// TOSS FUNCTION
unsigned int LRPlayer::toss( Potato &potato ){
unsigned int current; // current player
// Find who our current player is
for(unsigned int i=0; i<Players.size(); i++){
if(Players.at(i)->getId()==getId()){
current=i;
cout<<"A("<<i<<"), ";}
}
// if timer hasn't gone off yet...
if(potato.countdown()!=true){
// if this is the FIRST toss, we want to toss left
if(lrpFLAG==false){
if(current==0){
lrpFLAG=true;
(Players.at(Players.size()-1))->toss(potato);}
else{
lrpFLAG=true;
(Players.at(current-1))->toss(potato);}
}
else{
if(current==Players.size()-1){
lrpFLAG=false;
(Players.at(0))->toss(potato);}
else{
lrpFLAG=false;
(Players.at(current+1))->toss(potato);}
}
}
return (Players.at(current))->getId();
}
Main.cc
#include <iostream>
#include <vector>
#include <time.h>
#include "potato.h"
#include "player.h"
#include "umpire.h"
#include "PRNG.h"
using namespace std;
int main(int argc, char *argv[] ){
int p = 5;
int tmp;
unsigned int s;
PRNG prng1;
prng1.seed(1234567890);
// Parse the command line arguments
switch ( argc ) {
case 3:
tmp=atoi(argv[1]);
s=atoi(argv[2]);
prng1.seed(s);
if(tmp<2 || tmp>20){
cout << "Player must be between 2 and 20 inclusive" << endl;
return 0;}
else{
p = atoi(argv[1]);}
}
// Creating list of players.
Player::PlayerList players;
for(int i=0; i<p; i++){
if(i%2==0){
players.push_back(new LRPlayer(i,players));}
else{
players.push_back(new RNPlayer(i,players));}
}
//for (int i=0;i<players.size();i++){
// cout << "Player at " << i << " id: " << players.at(i)->getId() << endl;}
// How many players?----------------------------------------------------------------------
cout << p << " players in the match" << endl;
// Construct an UMPIRE--------------------------------------------------------------------
Umpire u(players);
// Start the game!------------------------------------------------------------------------
u.start();
}
Also note: PRNG.h is a class that generates a random number. so PRNG prng1; int rand=prng1(#) generates a random number between 0 and #.
ALSO:
The problem is occurring when i call my toss function. I'm not out of range because when i try to call Players.at(randU)->getID() i don't get any errors at all. Could it be that i can't reach the toss function for that player?I'm thinking it has to do with something im pointing to or memory. I first make a PlayerList players in my main.cc and push_back players alternating between the two. But each player also takes in a list. Maybe I'm running into errors involved with this?
Thanks! Any help is much appreciated :)
The exception thrown must be std::out_of_range. The random number you are generating must be higher than the number of elements in the vector.
randU must be re-generated after Players.erase() is called. Otherwise it will go out of range.
Or you should break the loop as:
for(unsigned int i=0; i<Players.size(); i++){
if(Players.at(i)->getId()==Players.at(randU)->toss(*f)){
Players.erase(Players.begin()+i);
cout << "Eliminated: "<< i << endl;
cout.flush();
break; // BREAK HERE as randU now can be greater than (Players.size() - 1)
}
}