结构体数组怎么初始化
3个回答
2013-08-12
展开全部
// 有两种方法可以初始化结构体数组,如下例所示:
#include <iostream>
#include <string>
#include <iomanip>
#include <memory>
using namespace std;
// custom_type
typedef struct tagStudent
{
int Id;
string Name;
}Student;
int main()
{
// 设置左对齐
cout.flags(ios::left);
// 方式1: 适用于提前知道具体数据的情况
Student arrStu1[5] = {{1, "Name_1"}, {2, "Name_2"}, {3, "Name_3"}, {4, "Name_4"}, {5, "Name_5"}};
cout<<"Method_1:"<<endl;
for (int i=0; i<5; i++)
{
cout<<setw(4)<<"Id:"<<arrStu1[i].Id<<", "
<<setw(6)<<"Name:"<<arrStu1[i].Name<<endl;
}
cout<<endl;
// 方式2: 具体数据可能稍后才能得到的情况
Student arrStu2[5];
memset(arrStu2, 0, sizeof(arrStu2));
cout<<"Method_2:"<<endl;
for (int i=0; i<5; i++)
{
cout<<setw(4)<<"Id:"<<arrStu2[i].Id<<", "
<<setw(6)<<"Name:"<<arrStu2[i].Name<<endl;
}
cout<<endl;
}
// 测试结果:
#include <iostream>
#include <string>
#include <iomanip>
#include <memory>
using namespace std;
// custom_type
typedef struct tagStudent
{
int Id;
string Name;
}Student;
int main()
{
// 设置左对齐
cout.flags(ios::left);
// 方式1: 适用于提前知道具体数据的情况
Student arrStu1[5] = {{1, "Name_1"}, {2, "Name_2"}, {3, "Name_3"}, {4, "Name_4"}, {5, "Name_5"}};
cout<<"Method_1:"<<endl;
for (int i=0; i<5; i++)
{
cout<<setw(4)<<"Id:"<<arrStu1[i].Id<<", "
<<setw(6)<<"Name:"<<arrStu1[i].Name<<endl;
}
cout<<endl;
// 方式2: 具体数据可能稍后才能得到的情况
Student arrStu2[5];
memset(arrStu2, 0, sizeof(arrStu2));
cout<<"Method_2:"<<endl;
for (int i=0; i<5; i++)
{
cout<<setw(4)<<"Id:"<<arrStu2[i].Id<<", "
<<setw(6)<<"Name:"<<arrStu2[i].Name<<endl;
}
cout<<endl;
}
// 测试结果:
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询