g
Oct 1, 2020 at 4:34pm UTC
gfgd
Last edited on Oct 4, 2020 at 2:09pm UTC
Oct 1, 2020 at 4:41pm UTC
Oct 1, 2020 at 4:54pm UTC
Consider:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
#include <vector>
#include <iostream>
#include <iomanip>
#include <string>
#include <ctime>
#include <cstdlib>
struct Pet {
std::string name;
std::string type;
int weight;
Pet(std::string& n, std::string& t, int w) : name(n), type(t), weight(w) {}
};
int main()
{
std::vector<Pet> pets;
int PetNum;
std::srand((unsigned )time(0));
std::cout << "How many pets do you have? " ;
std::cin >> PetNum;
for (int p = 0; p < PetNum; ++p) {
std::string PetName, PetType;
std::cout << "What is the name of your pet? " ;
std::cin >> PetName;
std::cout << "What type of pet is " << PetName << "? " ;
std::cin >> PetType;
pets.emplace_back(PetName, PetType, (rand() % 100) + 1);
}
std::cout << std::endl;
for (const auto & [name, type, weight] : pets) {
std::cout << "Pet Name: " << std::setw(15) << name << std::endl;
std::cout << "Pet Type: " << std::setw(15) << type << std::endl;
std::cout << "Pet Weight: " << std::setw(13) << weight << std::endl << std::endl;
}
}
Oct 1, 2020 at 6:14pm UTC
How would
Last edited on Oct 4, 2020 at 2:09pm UTC
Oct 1, 2020 at 6:31pm UTC
Change struct to class is the quickest way to change things. You'd also have to declare your member data and your ctor as public.
struct defaults to public access, class defaults to private.
1 2 3 4 5 6 7 8
struct Pet {
public :
std::string name;
std::string type;
int weight;
Pet(std::string& n, std::string& t, int w) : name(n), type(t), weight(w) {}
};
For better class encapsulation you'd want to have your data members be private, with methods to access/alter them.
Chapter 8 at Learn C++ would be a good start to learning about classes:
https://www.learncpp.com/cpp-tutorial/82-classes-and-class-members/
Oct 11, 2020 at 11:30pm UTC
jax16, do NOT delete your posts. That is RUDE and trollishly selfish. Others might have benefited from your questions and the answers. Not now.
Topic archived. No new replies allowed.