Access Struct in C++?

59 views Asked by At

I have a problem in c++ the teacher asking us to display a field of structures that contains n=100 students. Is this the right way to do it ?

#include <iostream>
#include <math.h>

using namespace std;

struct Students{
    string name;
    int id;
    int mark1;
    int mark2;
    int mark3;
};

int main(){
    int T[3];
    int i;

    for(i=0;i<=3;i++){
        T[i] = i;
    }
    for(i=0;i<=3;i++){
        Students T[i];
        cout<< T[i].name<<endl;
        cout<< T[i].id<<endl;
        cout<< T[i].mark1<<endl;
        cout<< T[i].mark2<<endl
        cout<< T[i].mark3<<endl;
    }
    return 0;
}
2

There are 2 answers

2
Vlad from Moscow On BEST ANSWER

The program does not make sense. You should either declare an array of type Students or use some other standard container as for example std::vector<Students>. And after the container will be defined you have to enter values for each element.

For example

const size_t N = 100;
Students students[N];

for ( size_t i = 0; i < N; i++ )
{
    std::cout << "Enter name of student " << i + 1 << ": ";
    std::cin >> students[i].name;
    // ...
}

Or

#include <vector>

//...

const size_t N = 10;
std::vector<Students> students;
students.reserve( N );

for ( size_t i = 0; i < N; i++ )
{
    Students s;
    std::cout << "Enter name of student " << i + 1 << ": ";
    std::cin >> s.name;
    // ...
    students.push_back( s );
}

To display the all ready filled container (an array or a vector) you can for example the range-based for statement

for ( const Students & s : students )
{
    std::cout << "Name " << s.name << std::endl;
    //...
}

or an ordinary for loop

for ( size_t i = 0; i < N; i++ )
{
    std::cout << "Name " << students[i].name << std::endl;
    //...
}

For a vector the condition of the loop will look

for ( std::vector<Students>::size_type i = 0; i < students.size(); i++ )
//...
1
Steephen On
    int T[3];
    int i;

    for(i=0;i<=3;i++){
        T[i] = i;
    }

Above code snippet correct as follows:

    Students T[3]; //Here you are creating only 3 students  record, 
                   //if it needed 100 change 3 to 100 and change
                   // boundary change in below for loop also
    for(int i=0;i<=3;i++){
        T[i].name=<>;
        T[i].id=<>;
      // upadte your array of structure students as follows: ....

    }