使函数调用在while循环之外工作。 [英] Making a function call work outside of a while loop.

查看:136
本文介绍了使函数调用在while循环之外工作。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对C ++很新,我正在构建一个模拟兔子群的程序。该程序将能够自动添加兔子,给他们的名字,年龄,颜色等。我正在寻找有关如何更改我的代码的建议,以便打印功能在while循环之外工作。



我尝试了什么:



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:

#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;
}

推荐答案

这很简单 - 直接从您的殖民地访问Bunny实例:

It's simple - just access a Bunny instance from your colony directly:
colony[0].printBunny();



Or

colony[3].printBunny();



Or

colony[5].printBunny();


这篇关于使函数调用在while循环之外工作。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆