question about using vectors

Hi! i'm pretty new at c++ and we've recently been learning about reading text files. So far we have just used getline and storing in a array/printing it out using a while loop and for loop iteration. I just wanted to know how you would want to store lines in separately like say you had a text file containing data on animals (age and weight) each on a separate line.
eg....
dog
5 (age)
10 (weight)
4 (age)
4
//blank line
cat
4 (age)
3 ..and so forth

if you had a fixed amount of animals for each type of animal, you could probably use an array, but how would you go about storing it in a vector and accessing, say, only the ages of dogs to get the average age?


You shoud create a struct describing animal and stor it in your vector:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
struct Animal
{
    std::string type;
    unsigned age;
    unsigned weight;
};

//...

std::vector<Animal> zoo;
Animal animal;
//Read from file in actual code
animal.type = "dog";
animal.age = 3;
animal.weight = 8;

zoo.push_back(animal);
for(const Animal& a: zoo)
    if(a.type == "dog")
        std::cout << a.age;



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
45
46
47
48
49
50
51
52

#include <iostream>
#include <string>
#include <vector>
using namespace std;

struct Animal
{
	string animalType;
	string animalName;
	int animalAge;
	//... and so on.

	// constructor
	Animal(string type, string name, int age) : animalType(type), animalName(name), animalAge(age) {}
	Animal() { animalType.clear(); animalName.clear(); animalAge = 0; }

};


int main()
{

	vector<Animal> animalList;

	// you can add data using the structures constructor
	animalList.push_back(Animal("Dog", "Shep", 9));
	animalList.push_back(Animal("Cat", "Polly", 3));
	animalList.push_back(Animal("Horse", "Angel", 12));

	// or create a object and populate it
	Animal Pig;

	Pig.animalName = "Harry";
	Pig.animalAge = 1;
	Pig.animalType = "Pig";

	// display Pig Info
	cout << Pig.animalName << endl;
	cout << Pig.animalType << endl;
	cout << Pig.animalAge << endl << endl;

	// display the rest in animalList.
	for (int i = 0; i < 3; i++)
	{
		cout << animalList[i].animalName << endl;
		cout << animalList[i].animalType << endl;
		cout << animalList[i].animalAge << endl << endl;
	}

}


Thank you :)
Topic archived. No new replies allowed.