struct is an interestng concept, if you understand structs, you could create an array of structs.
A struct is basically a group of two or more variables (of any type) that will always go toghether:
1 2 3 4
|
struct EXAMPLE_name {
int age;
char c;
};
|
Check out every symbol ({};) i used.
this should go above, before main. this creates some kind of new "variable" (it´s actually a struct, for structure, i guess) that will always have two variables inside. You didn´t create one struct, you created A TYPE, called EXAMPLE_name (use whatever name you want). then, in main:
1 2 3 4 5
|
...
EXAMPLE_name John = {34, c};
EXAMPLE_name Sean = {32, c};
EXAMPLE_name Lucy = {4, d};
...
|
you use that new type to store always togheter an int and a char.
(check out the "spelling" again).
To get to a field inside a struct (in this example you have two fields, age and c) you use this:
1 2 3 4
|
cout << "How old are you? " << endl;
cin << John.age;
cout >> "what´s your favorite letter?" << endl;
cin << John.c;
|
So, in your program, you always have
an int (age)
a char (c)
going hand in hand inside a new type (struct) designed by you.
If you get the power of that, and how it´ll simplify a lot of situations, the next step is easy.
Say you want to store the age and favourite letter of everyone in your family (god knows why you´re coming along with such a crazy idea), you could create an array of EXAMPLE_name. Yes!
not an array of int...
not an array of char...
not an array of double...
no,
an array of EXAMPLE_name...
an array of the struct you defined.
1 2 3 4 5 6 7 8
|
EXAMPLE_name my_family[5];
for (int i = 0; i < 5; i++){
cout << "How old are you? " << endl;
cin << my_family[i].age;
cout >> "what´s your favorite letter?" << endl;
cin << Jmy_family[i].c;
}
|
You use the power of iterations to initialize them!
Hope you get it (I´m quite new to this). Anyway, if the explanation is missing something, anyone is wellcome to improve it, but you should know that the concept that will help you is STRUCT.
Bye!