Home > OS >  Accessing structure array attributes without using pointers
Accessing structure array attributes without using pointers

Time:10-12

Is it possible to make a structure array variable and access structure attributes without using pointers? I tried doing it without a pointer and it is giving me an error.

#include<iostream>
#include<string>
using namespace std;
struct Student
{
    string name;
    string rollNo;
    float GPA;
    string department;
    char section;
};

int main()
{
    Student s1[10];
    
    for (int i = 0; i < 10; i  )
    {
        cout << i   1 << "Enter your name: ";
        cin >> s1.name;
        cout << "Enter roll num: ";
        cin >> s1.rollNo;
    }

return 0;
}

I am accessing attributes by placing a dot s1.rollNo gives an error.

CodePudding user response:

s1 is an array of structs and needs to be accessed with an index: s1[i].name etc.

CodePudding user response:

As said by others you need to access it like

s1[i].name

You could also access it like

for(auto &s : s1){
    cin >> s.name; //Do Whatever With Member
}
  • Related