结构体是什么?
struct是自定义数据类型,是一些类型集合组成的一个类型。
 
结构体的定义方式
#include<iostream>
using namespace std;
struct Student
{
	string name;
	int age;
	int score;
};
 
创建结构体变量并赋值
方式一,先创建结构体变量,再赋值
// 创建结构体变量 , 此时可以省略struce关键字
struct Student s1;
// 给结构体变量赋值
s1.name = "zhangsan";
s1.age = 26;
s1.score = 100;
 
方式二,创建结构体变量的同时赋值
struct Student s2={"zhangsan",26,100};
 
方式三,创建结构体的时候顺便创建结构体变量
struct Student
{
	string name;
	int age;
	int score;
}s3;
s3.name = "zhangsan";
s3.age = 26;
s3.score = 80;
 
结构体数组的定义和访问
#include<iostream>
#include<string>
using namespace std;
struct Student
{
    string name;
    int age;
    int score;
};
int main()
{
    struct Student stu_arr[3] = 
    {
        {"张三",18,80},
        {"李四",19,60},
        {"王五",38,66}
    };
    // 给结构体的元素赋值
    stu_arr[2].name = "赵六";
    stu_arr[2].age = 20;
    stu_arr[2].score = 98;
    // 遍历结构体数组
    for(int i=0;i<3;i++)
    {
        cout<<"姓名:"<<stu_arr[i].name<<"年龄: "<<stu_arr[i].age<<"分数: "<<stu_arr[i].score<<endl;
    }
    return 0;
}
 
编译和执行
 
C++输出string类型必须引入 #include
# 使用输入命令输出报错
cout<<"姓名"<<s1.name<<"年龄"<<s1.age<<endl;
 
因为s1.name是string类型,C++输出string类型必须引入 #include<string>
                


















