在 C++ 中访问结构?

Access Struct in C++?

我在 C++ 中遇到问题 老师要求我们展示一个包含 n=100 名学生的结构域。这是正确的做法吗?

#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;
}

程序没有意义。您应该声明一个 Students 类型的数组或使用其他一些标准容器,例如 std::vector<Students>。在定义容器后,您必须为每个元素输入值。

例如

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;
    // ...
}

或者

#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 );
}

要显示所有准备好的填充容器(数组或向量),您可以例如基于范围的 for 语句

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

或者一个普通的for循环

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

对于向量,循环条件看起来

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

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

以上代码片段更正如下:

    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: ....

    }