结构体知识点(string的一些小用法/随机数的生成)

结构体基本概念

结构体定义和使用

在C++种,在创建变量是,struct关键字可以省略,结构体定义时不可以省略

结构体数组

结构体指针

结构体嵌套结构体

#define _CRT_SECURE_NO_WARNINGS 
#include<iostream>
using namespace std;
struct student
{
	string name;
	int age;
	int score;
};

struct teacher
{
	int id;
	string name;
	struct student std;
};
int main()
{
	teacher t;
	t.id = 10000;
	t.name = "韩老师";
	t.std.name = "王学生";
	t.std.age = 18;
	t.std.score = 100;

	cout << "老师的编号为:		" << t.id << endl
		<< "老师的姓名为:		" << t.name << endl
		<< "所带学生的姓名为:	" << t.std.name << endl
		<< "所带学生的年龄为:	" << t.std.age << endl
		<< "所带学生的成绩为:	" << t.std.score << endl;

	system("pause");
	return 0;
}

结构体做函数参数

结构体中const的使用场景

结构体案例

案例一

#define _CRT_SECURE_NO_WARNINGS 
#include<iostream>
using namespace std;
struct student
{
	string name;
	int score;
};
struct teacher
{
	string name;
	student stu[5];
};
int main()
{
	teacher ter[3];
	int i = 0;
	int j = 0;

	//赋值
	for (i = 0; i < 3; i++)
	{
		cout << "请输入第" << i+1 << "个老师的姓名:" ;
		cin >> ter[i].name;
		for (j = 0; j < 5; j++)
		{
			cout << "请输入第" << j + 1 << "个学生的姓名:" ;
			cin >> ter[i].stu[j].name;
			cout << "请输入第" << j + 1 << "个学生的分数:" ;
			cin >> ter[i].stu[j].score;
		}
	}

	//输出
	for (int i = 0; i < 3; i++)
	{
		cout << "第" << i + 1 << "个老师的姓名为:" << ter[i].name << endl;
		for (j = 0; j < 5; j++)
		{
			cout << "		" << "第" << j + 1 << "个学生的姓名为:" << ter[i].stu[j].name << endl;
			cout << "		" << "第" << j + 1 << "个学生的成绩为:" << ter[i].stu[j].score << endl;
		}
	}

	system("pause");
	return 0;
}

案例二

#define _CRT_SECURE_NO_WARNINGS 
#include<iostream>
using namespace std;
struct Hero
{
	string name;
	int age;
	string sex;
};
int main()
{
	Hero h[5] = {
		{"刘备",23,"男"},
		{"关于",22,"男"},
		{"张飞",20,"男"},
		{"赵云",21,"男"},
		{"貂蝉",19,"女"}
	};
	int i = 0;
	int j = 0;
	//冒泡排序
	for (i = 0; i < 4; i++)
	{
		for (j = 0; j < 4 - i; j++)
		{
			if ((h[j].age) > (h[j + 1].age))
			{
				Hero temp = h[j];
				h[j] = h[j + 1];
				h[j + 1] = temp;
			}
		}
	}
	//输出
	for (i = 0; i < 5; i++)
	{
		cout << h[i].name << "\t" << h[i].age << "\t" << h[i].sex << endl;
	}

	system("pause");
	return 0;
}

string的加法运算

直接在后面追加字符

#define _CRT_SECURE_NO_WARNINGS 
#include<iostream>
using namespace std;
int main()
{
	string name = "abd";
	name += "cd";//可追加任意长度

	cout << name << endl;//abdcd

	system("pause");
	return 0;
}

随机数的生成

包含头文件

#include<ctime>

    srand((unsigned int)time(NULL));

    cout<<rand();

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值