So you have a bunch of properties, name
, lname
and num
, and you want to store all of them.
To store multiple objects as a collection, the std::vector
is usually a good container. You can use it like this to solve your problem:
std::vector<std::string> names; // this vector contains each name
std::vector<std::string> lnames; // this vector contains each lname
std::vector<std::string> nums; // this vector contains each num
for(i=0;i<n;i++)
{
std::string name, lname, num;
std::cin >> name >> lname >> num;
names.push_back(name); // adds `name` to the `names` vector
lnames.push_back(lname); // adds `lname` to the `lnames` vector
nums.push_back(num); // adds `num` to the `nums` vector
}
for(i=0;i<n;i++)
{
std::cout << names.at(i) << " "; // prints the name at index i in `names`
std::cout << lnames.at(i) << " "; // prints the corresponding lname in `lnames`
std::cout << nums.at(i) << std::endl; // prints the corresponding num in `nums`
}
This is not the best solution however. Since your name
, lname
and num
variables essentially represent a person, it would be good to define a class to hold all the data of a single person. The class could be called Person
, for example:
class Person
{
public:
std::string name;
std::string lname;
int num;
};
Now that we have our Person
class we can simply define a single vector to hold all our Person
instances:
std::vector<Person> persons;
for(i=0;i<n;i++)
{
Person person; // creates a new Person object
// now let's read the name, lname and num for that person:
std::cin >> person.name;
std::cin >> person.lname;
std::cin >> person.num;
// and add the person to the list of persons
persons.push_back(person);
}
To print out the persons from the vector, we can now simply do this:
for(i=0;i<n;i++)
{
std::cout << persons.at(i).name << " " << persons.at(i).lname << " " << persons.at(i).num << std::endl;
}
This could be of course improved even further but I'll let you learn it yourself.