结构体和数组结合使用

1、定义结构体

struct Student
{
	int num;
	char name[32];
};

2、结构体数组定义

#include<iostream>
using namespace std;

struct Student
{
	int num;
	char name[32];
};
int main()
{
	//结构体变量复制方式2
	struct Student arr[2] = { {1,"张三"}, {2,"李四"}};
	system("pause");  
	return 0;
}

3、结构体数组输出

#include<iostream>
using namespace std;

struct Student
{
	int num;
	char name[32];
};
int main()
{
	//结构体变量复制方式2
	struct 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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值