1、定义结构体
struct Student
{int num;char name[32];
};
2、结构体数组定义
#include<iostream>
using namespace std;struct Student
{int num;char name[32];
};
int main()
{//结构体变量复制方式2struct Student arr[2] = { {1,"张三"}, {2,"李四"}};system("pause"); return 0;
}
3、结构体数组输出
#include<iostream>
using namespace std;struct Student
{int num;char name[32];
};
int main()
{//结构体变量复制方式2struct Student arr[2] = { {1,"张三"}, {2,"李四"}};cout << arr[0].name << arr[0].num << "\n" << arr[1].name << arr[1].num << endl;system("pause"); return 0;
}
结果如下所示:
4、结构体数组应用-选民系统
#include<iostream>
using namespace std;struct X_min
{char name[32];int tickets;
};
int main()
{struct X_min x_m[3];struct X_min max;int invalidated_ticket = 0;int i, j, len;int mark = 0;int total = 5;char temName[32];len = sizeof(x_m) / sizeof(x_m[0]);//初始化选民信息for (i = 0; i < len;i++) {x_m[i].tickets = 0;cout << "请输入第" << i + 1 << "个选民的名字\n" << endl;cin >> x_m[1].name; }//读票环节for (i < 0; i < total; i++) {mark = 0;cout << "请输入你投给谁:\n" << endl;memset(temName,'\0',sizeof(temName));//每次清空一下cin >> temName;for (j = 0; j < len; j++) {if (strcmp(temName, x_m->name) == 0) {x_m->tickets++; mark = 1;}}if (mark == 0) {cout << "没有该候选人" << endl;invalidated_ticket++;}}//选票结果for (i = 0; i < len; i++) {cout << "名字:" << x_m->name << "票数" << x_m->tickets << "\n" << endl;}max = x_m[0];for (i = 1 ; i < len; i++) {if (max < max[i]) {max = x_m[i];}}cout << max.name << "以" << max.tickets << "当选" << "\n" << "其中废票:" << invalidated_ticket << endl;system("pause"); return 0;
}