C++中的访问结构

Access Struct in C++?

本文关键字:结构 访问 C++      更新时间:2023-10-16

我在 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: ....
    }