在C ++中访问Struct?

时间:2015-06-14 18:16:57

标签: c++ matrix structure

我在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;
}

2 个答案:

答案 0 :(得分: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++ )
//...

答案 1 :(得分:0)

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

    }

以上代码段正确如下:

requests.get(url,headers={'Authorization': 'GoogleLogin auth=%s' % authorization_token})