my_name
my_name

Reputation: 51

How to set up a number of objects

void Dog::readDog()
{
    cout << "Name: ";
    cin >> this->name;
    cout << "height: ";
    cin >> this->height;
    cout << "weight: ";
    cin >> this->weight;
    cout << "Color: ";
    cin >> this->color;
}
void Dog::printDog()
{
    cout << "Name: " << this->name << endl;
    cout << "Height: " << this->height << endl;
    cout << "Weight: " << this->weight << endl;
    cout << "Color: " << this->color << endl;
}

int main() {
    Dog dogs;
    int n;
    cout << "Number of dogs to introduce: ";
    cin >> n;
    
    dogs.readDog();
    dogs.printDog();

}

this is a part of my code and i have a little problem because i forgot how to set up a number of dogs that i want to introduce in program, e.g. i want 3 dogs : Max, Rex, Terry. My program read and print just one dog

Upvotes: 0

Views: 183

Answers (1)

user12002570
user12002570

Reputation: 1

You can use a std::vector for creating a container that will contain n number of Dog objects as shown below:

#include <iostream>
#include <vector>
#include <string>
class Dog 
{
  public:
      void readDog();
      void printDog();
  private:
    std::string name, color;
    double height, weight;
};

void Dog::readDog()
{
    std::cout << "Name: ";
    std::cin >> this->name;
    std::cout << "height: ";
    std::cin >> this->height;
    std::cout << "weight: ";
    std::cin >> this->weight;
    std::cout << "Color: ";
    std::cin >> this->color;
}
void Dog::printDog()
{
    std::cout << "Name: " << this->name << std::endl;
    std::cout << "Height: " << this->height << std::endl;
    std::cout << "Weight: " << this->weight << std::endl;
    std::cout << "Color: " << this->color << std::endl;
}

int main() {
    Dog dogs;
    int n;
    std::cout << "Number of dogs to introduce: ";
    std::cin >> n;
    
    std::vector<Dog> vecDogs(n); //create a vector (of size n) of Dog objects 
    for(int i = 0; i < n; ++i)
    {
        vecDogs.at(i).readDog();
        vecDogs.at(i).printDog();
    }
    
}

std::vector is a variable size container which means you can use it to have n number of Dog objects, where n need not be a constant expression.

The output of the above program can be seen here.

Upvotes: 2

Related Questions