STRUCT – Definition And Access To Data

A record is a grouping of data, which are not necessarily of the same type. They are defined with the word “struct”.

To access each of the data that form the record, whether we want to read its value or if we want to change it, we must indicate the name of the variable and the data (or field) separated by a point:

// Introduction to C ++, Nacho Cabanes
// Example 07.01:
// Registers (struct)

#include <iostream>
using namespace std;

int main ()
{
struct
{
string name;
initial char;
int age;
float note;
} person;

persona.name = “Juan”;
person.initial = ‘J’;
person.edad = 20;
person.note = 7.5;
cout << “Age is” << person.edad;

return 0;
}

As usual in C ++, to declare the variable we have first indicated the data type (struct {…}) and then the name that variable (person) will have.

We can also declare first how our records are going to be, and later define variables of that type:

// Introduction to C ++, Nacho Cabanes
// Example 07.02:
// Records (2)

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

int main ()
{
struct dataPerson
{
string name;
initial char;
int age;
float note;
};

dataPerson person;

persona.name = “Juan”;
person.initial = ‘J’;
person.edad = 20;
person.note = 7.5;
cout << “Age is” << person.edad;

return 0;
}

Proposed exercises:

(7.1.1) A ?? struct ?? that stores data of a song in MP3 format: Artist, Title, Duration (in seconds), File size (in KB). A program must request the data of a song from the user, store them in said ?? struct ?? and then display them on the screen.
7.2. Record arrays
We have saved several data of a person. You can store those of several people if we combine the use of “struct” with the tables (arrays) that we saw earlier. The syntax is not exactly the same, and we will have to add the word “new” at the time of reserving space. For example, if we want to save the data of 100 students we could do:

// Introduction to C ++, Nacho Cabanes
// Example 07.03:
// Array of records

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

int main ()
{
struct dataPerson
{
string name;
initial char;
int age;
float note;
};

dataPerson * person = new dataPerson [50];

for (int i = 0; i <5; i ++)
{
cout << “Tell me the name of the person” << i << endl;
cin >> person [i] .name;
}

cout << “Person 3 is” << person [2] .name << endl;

return 0;
}

The initial of the first student would be “students [0]. Initial”, and the age of the last would be “students [99]. Age”

You may also like...

1 Response

  1. 2017

    […] Previous story STRUCT – Definition And Access To Data […]

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

error: Content is protected !!