Click here to Skip to main content
15,889,808 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I fairly new to C++ and I am constructing a program that is to simulate a colony of bunnies. The program will be able to automatically add bunnies, give them names, ages, color etc. I am looking for advice on how I could change my code so that the print function will work outside of the while loop.

What I have tried:

C++
#include <iostream>
#include <ctime>
#include <vector>
#include <cstdlib>

using namespace std;

const int  POSSIBLE_NAMES = 18;
const int  POSSIBLE_COLORS = 4;

static std::string possibleNames[] ={
    "Jen",
    "Alex",
    "Janice",
    "Tom",
    "Bob",
    "Cassie",
    "Louis",
    "Frank",
    "Bugs",
    "Daffy",
    "Mickey",
    "Minnie",
    "Pluto",
    "Venus",
    "Topanga",
    "Corey",
    "Francis",
    "London",
};
static std::string possibleColors[] ={

    "White",
    "Brown",
    "Black",
    "Spotted"
};

struct Bunny
{
public:

string name;
int age;
string color;
char sex;

Bunny(){
    setSex();
    setColor();
    setAge(0);
    setName();
}

int randomGeneration(int x){
    return rand() % x;
}

void setSex()
{
    int randomNumber = randomGeneration(2);

    ( randomNumber == 1 ) ? sex = 'm' : sex = 'f';
}

char getSex()
{
    return sex;
}

void setColor()
{
    int randomNumber = randomGeneration(POSSIBLE_COLORS);
    color = possibleColors[randomNumber];
}

string getColor()
{
    return color;
}

void setAge(int age)
{
    this->age = age;
}

int getAge()
{
    return age;
}

void setName()
{
    int i = randomGeneration(POSSIBLE_NAMES);
    name = possibleNames[i];
}

string getName()
{
    return name;
}

void printBunny()
{
    cout << "Name: " << getName() << endl;
    cout << "Sex: " << getSex() << endl;
    cout << "Color: " << getColor() << endl;
    cout << "Age: " << getAge() << endl;
}
};

int main()
{

int i;
vector< Bunny > colony;

 
while(i > 6)
{
    colony.push_back( Bunny() );
	colony[i].printBunny();//<-- I want this to be able to happen outside the while loop
	cout << endl;
	i++;
}

return 0;
}
Posted
Updated 18-Mar-17 20:43pm

1 solution

It's simple - just access a Bunny instance from your colony directly:
colony[0].printBunny();
Or
colony[3].printBunny();
Or
colony[5].printBunny();
 
Share this answer
 
Comments
Member 12863707 19-Mar-17 3:19am    
But what if I wanted to access them all?
OriginalGriff 19-Mar-17 4:04am    
You can't access them all at once, any more than you can drive three cars at the same time! :laugh:

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900