line 9 is an archaic leftover from C and I advise not doing it. It makes a global variable, called s, that is an array of 10 of the structures.
Better to treat student as a type, and say
student s[10]; //inside main, like any other variable.
s[i] is standard array indexing. Have you studied arrays at all? They normally come BEFORE structures!
structures in c++ work just like classes in c++, except that classes have private data by default (can be changed with keyword public) and structs have public by default (can be changed with private keyword). The most basic structs and classes are just compound variables, they group several types together into one new type, as you see here you have a C style string, an integer, and a float all grouped together as a single type. As you advance, you can add functions to the types as well, and many more things.
Consider using c++ strings (include <string>, and the type is string) instead of C's character arrays. Wherever you got this code... it looks like C pretending to be C++... maybe try to find a better example.
here: exactly the same, but modernized a bit
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
|
struct student
{
string name;
int roll{};
float marks{};
};
int main()
{
student s[10];
cout << "Enter information of students: " << endl;
// storing information
for(int i = 0; i < 10; ++i)
{
s[i].roll = i+1;
cout << "For roll number" << s[i].roll << "," << endl;
cout << "Enter name: ";
cin >> s[i].name;
cout << "Enter marks: ";
cin >> s[i].marks;
cout << endl;
}
cout << "Displaying Information: " << endl;
// Displaying information
for(int i = 0; i < 10; ++i)
{
cout << "\nRoll number: " << i+1 << endl;
cout << "Name: " << s[i].name << endl;
cout << "Marks: " << s[i].marks << endl;
}
return 0;
}
| |