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: ....
}
相关文章:
- 通过方法访问结构
- 使用不带参数的函数访问结构元素
- 访问存储在向量C++中的结构的多态成员
- 访问类lintalizer列表中的结构元素
- 仅使用结构名称访问结构成员
- 如何从其他结构访问受保护的结构变量
- 如何从类中定义的结构访问私有成员?c++
- 枚举范围无法通过 C++ 中的类中的结构访问
- 通过更高级别的结构访问子变量
- 从匿名结构访问枚举条目
- 如何定义别名以通过结构访问枚举类成员
- C 用于向量中的结构访问索引或使用参考值
- 奇怪的结构访问错误
- 将数组作为结构访问与未定义的行为
- 使用c++以及x86和x64体系结构访问处理器中断
- 使用 ostream 从另一个类的结构访问数据
- 从结构访问数组会使程序崩溃
- 联合中的C++结构访问联合成员
- SWIG如何使用Lua表从Lua中的c结构访问字节数组
- c++结构访问冲突